简体   繁体   English

从单独的列表创建字典列表

[英]Creating a list of dictionaries from separate lists

I honestly expected this to have been asked previously, but after 30 minutes of searching I haven't had any luck. 老实说我以前曾经问过这个问题,但经过30分钟的搜索,我没有运气。

Say we have multiple lists, each of the same length, each one containing a different type of data about something. 假设我们有多个列表,每个列表具有相同的长度,每个列表包含关于某些内容的不同类型的数据。 We would like to turn this into a list of dictionaries with the data type as the 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 fairly 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! 但这是2017年! There has to be a more concise way to do this! 必须有一个更简洁的方法来做到这一点! We have map, flatmap, reduce, list comprehensions, numpy, lodash, zip. 我们有map,flatmap,reduce,list comprehensions,numpy,lodash,zip。 Except I can't seem to compose these cleanly into this particular transformation. 除了我似乎无法将这些干净地组合成这种特殊的转变。 Any ideas? 有任何想法吗?

You can use a list comprehension with zip after transposing your dataset: 转置数据集后,您可以使用带有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}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM