[英]Python - Create list of dictionaries from multiple lists of values
I have multiple lists of data, for example: age, name, gender, etc. All of them in order, meaning that the x record of every list belongs to the same person.我有多个数据列表,例如:年龄、姓名、性别等,都是按顺序排列的,意思是每个列表的x记录属于同一个人。
What I'm trying to create is a list of dictionaries from these lists in the best pythonic way.我想要创建的是以最佳 pythonic 方式从这些列表中创建的字典列表。 I was able to create it using one of the lists, but not sure how to scale it from there.
我能够使用其中一个列表创建它,但不确定如何从那里扩展它。
What I currently have:我目前拥有的:
ages = [20, 21, 30]
names = ["Jhon", "Daniel", "Rob"]
list_of_dicts = [{"age": value} for value in ages]
It returns:它返回:
[{'age': 20}, {'age': 21}, {'age': 30}]
What I want:我想要的是:
[{'age': 20, 'name': 'Jhon'}, {'age': 21, 'name': 'Daniel'}, {'age': 30, 'name': 'Rob'}]
ages = [20, 21, 30]
names = ["Jhon", "Daniel", "Rob"]
list_of_dicts = [{"age": value, 'name': name}
for value, name in zip(ages, names)]
You can take this one step further and use a double zip (useful if you have many more keys):您可以更进一步并使用双拉链(如果您有更多钥匙,则很有用):
keys = ['ages', 'names']
lists = [ages, names]
list_of_dicts = [dict(zip(keys, x)) for x in zip(*lists)]
output:输出:
[{'age': 20, 'name': 'Jhon'},
{'age': 21, 'name': 'Daniel'},
{'age': 30, 'name': 'Rob'}]
Less obvious code than @mozway's, but has imho one advantage - it relies only on a single definition of a mapping dictionary so if you need to add/remove keys you have to change only one k:v pair.与@mozway 相比,代码不太明显,但有一个优势——它仅依赖于映射字典的单一定义,因此如果您需要添加/删除键,则只需更改一对 k:v 对。
ages = [20, 21, 30]
names = ["Jhon", "Daniel", "Rob"]
d = {
"name" : names,
"age" : ages
}
list_of_dicts = [dict(zip(d,t)) for t in zip(*d.values())]
print(list_of_dicts)
For Fun:) You can use functools.reduce
:为了好玩:)你可以使用
functools.reduce
:
>>> from functools import reduce
>>> reduce (lambda l,t: l+[{'name':t[0] , 'age':t[1]}], zip(ages, names), [])
[{'name': 20, 'age': 'Jhon'},
{'name': 21, 'age': 'Daniel'},
{'name': 30, 'age': 'Rob'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.