Creating a list of dictionaries from separate lists

I honestly expected this to be asked earlier, but after 30 minutes of searching I was out of luck.

Let's say we have several lists, each of which has the same length, each of which contains data on different types. We would like to turn this into a list of dictionaries with a data type as a key.

input:

data = [['tom', 'jim', 'mark'], ['Toronto', 'New York', 'Paris'], [1990,2000,2000]]
data_types = ['name', 'place', 'year']

output:

travels = [{'name':'tom', 'place': 'Toronto', 'year':1990},
        {'name':'jim', 'place': 'New York', 'year':2000},
        {'name':'mark', 'place': 'Paris', 'year':2001}]

This is pretty easy to do with index-based iteration:

travels = []
for d_index in range(len(data[0])):
    travel = {}
    for dt_index in range(len(data_types)):
        travel[data_types[dt_index]] = data[dt_index][d_index]
    travels.append(travel)    

But this is 2017! There must be a more concise way to do this! We have map, flat map, abbreviation, lists, numpy, lodash, zip. Except that I cannot compose this data in this particular transformation. Any ideas?

+4
source share
1

zip :

>>> [dict(zip(data_types, x)) for x in zip(*data)]
[{'place': 'Toronto', 'name': 'tom', 'year': 1990}, 
 {'place': 'New York', 'name': 'jim', 'year': 2000}, 
 {'place': 'Paris', 'name': 'mark', 'year': 2000}]
+10

Source: https://habr.com/ru/post/1676847/


All Articles