Python - how to populate a list of dictionaries from existing lists

I have list

lists for example. mylist=[[1,2,3],[4,5,6],[7,8,9],...]

and I want to fill in list

of dict

where the dicts values ​​come from nested lists eg.

dlist[0]['area']=1
dlist[0]['volume']=2
dlist[0]['height']=3
dlist[1]['area']=4
dlist[1]['volume']=5

      

and etc.

So far I have:

dlist = [{'area':mylist[i][0], 'volume':mylist[i][1], 'height':mylist[i][2]} for i in range(len(mylist)]

      

My lists can be very large in the first dimension (i.e., they len(mylist)

can be very large). Is there a faster way than understanding this list? Maybe something with zip

?

+3


source to share


1 answer


You can use zip

in understanding list

:

Code:

keys = ('area', 'volume', 'height')
output = [dict(zip(keys, l)) for l in mylist]

      

Data:

mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

      

Results:

[{'volume': 2, 'height': 3, 'area': 1},
 {'volume': 5, 'height': 6, 'area': 4},
 {'volume': 8, 'height': 9, 'area': 7}]

      

But if you want faster than your original solution:

Then skip zip

, use iteration in original list

and create dict

directly:

output = [{'area': i[0], 'volume': i[1], 'height': i[2]} for i in mylist]

      



Timing:

import timeit

mylist = [[1, 2, 3]] * 100000

def method1():
    keys = ('area', 'volume', 'height')
    return [dict(zip(keys, i)) for i in mylist]

def method2():
    return [{
        'area': mylist[i][0],
        'volume': mylist[i][1],
        'height': mylist[i][2]
    } for i in range(len(mylist))]

def method3():
    return [{'area': i[0], 'volume': i[1], 'height': i[2]} for i in mylist]

print(timeit.repeat("method1()", "from __main__ import method1", number=10))
print(timeit.repeat("method2()", "from __main__ import method2", number=10))
print(timeit.repeat("method3()", "from __main__ import method3", number=10))

      

Synchronization results:

Country:

[1.192184281360701, 1.7045185775655127, 1.2134081278821043]

      

Original:

[0.38957559529443664, 0.38713287436332866, 0.3920681133687083]

      

Iterating over a list, directly creating a dict:

[0.2965552921248671, 0.28165834370140264, 0.29972900470716013]

      

+5


source







All Articles