Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!!

like image 910
retr0327 Avatar asked Nov 27 '22 16:11

retr0327


1 Answers

dct = [{'int':a,'str':b,'float':c}  for a,b,c in zip(list_1,list_2,list_3)]
like image 82
Tim Roberts Avatar answered Dec 19 '22 11:12

Tim Roberts