How do I create a list of dictionaries with same keys?

Viewed 689

Let's say I got three lists below:

list_1 = [1, 2, 3, 4, 5]           # five ints
list_2 = ['a', 'b', 'c', 'd', 'e'] # five strs
list_3 = [1.1, 2.2, 3.3, 4.4, 5.5] # five floats

How can combine these three lists to this:

[
    {'int': 1, 'str': 'a', 'float': 1.1}, 
    {'int': 2, 'str': 'b', 'float': 2.2}, 
    {'int': 3, 'str': 'c', 'float': 3.3}, 
    {'int': 4, 'str': 'd', 'float': 4.4}, 
    {'int': 5, 'str': 'e', 'float': 5.5}
]

What is the syntactically cleanest way to accomplish this?

Thanks for any help!!

3 Answers
dct = [{'int':a,'str':b,'float':c}  for a,b,c in zip(list_1,list_2,list_3)]

Try using zip().

It basically iterates through [(1, 'a', 1.1), (2, 'b', 2.2), (3, 'c', 3.3), (4, 'd', 4.4), (5, 'e', 5.5)], pairs this with your keys ["int","str","float"] and creates a list of dictionaries with this.

compact

dictList = [{k:v for k,v in zip(['int','str','float'],pair)} for pair in zip(list_1,list_2,list_3)]

readable for the human eye

dictList = []
for pair in zip(list_1,list_2,list_3):
    dicts1 = {}
    for k,v in zip(['int','str','float'],pair):
        dicts1[k] = v
    dictList.append(dicts1)

hardcoded a tad bit

dictList = [{'int':x,'str':y,'float':z} for x,y,z in zip(list_1,list_2,list_3)]

output

[
    {'int': 1, 'str': 'a', 'float': 1.1}, 
    {'int': 2, 'str': 'b', 'float': 2.2}, 
    {'int': 3, 'str': 'c', 'float': 3.3}, 
    {'int': 4, 'str': 'd', 'float': 4.4}, 
    {'int': 5, 'str': 'e', 'float': 5.5}
]

This is similar to @Tim Roberts solution, but allows for arbitrary typing.

[dict(((type(x).__name__,x) for x in (a,b,c))) for a,b,c in zip(list_1,list_2,list_3)]
Related