[英]How do you join a list to a dictionary of lists as a new item - python?
Maybe a simple question: 也许是一个简单的问题:
In python I have a list of dictionaries and I want to add a list as new item in every dictionary in the list? 在python中,我有一个字典列表,我想在列表中的每个字典中添加一个列表作为新项?
For example I have the list of dictionaries: 例如,我有字典列表:
list_dict =[{'id':1, 'text':'John'},
{'id':2, 'text':'Amy'},
{'id':3, 'text':'Ron'}]
And a list: 并列出:
list_age = [23, 54, 41]
How could I then add the list to produce the list of dictionaries: 然后,如何添加列表以生成字典列表:
list_dict =[{'id':1, 'text':'John', 'age':23},
{'id':2, 'text':'Amy', 'age':54},
{'id':3, 'text':'Ron', 'age':41}]
I am unsure of the correct code to use here? 我不确定在这里使用正确的代码吗?
Use zip
, to iterate over the matching pairs and update the dicts: 使用
zip
,遍历匹配对并更新字典:
>>> for d, a in zip(list_dict, list_age):
... d["age"] = a
...
>>> list_dict
[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]
Try this loop if list_age
and list_dict
are of same length : 如果
list_age
和list_dict
的长度相同,请尝试以下循环:
for i, j in zip(list_dict, list_age):
i['age']=j
OUTPUT : 输出 :
[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]
Add the list to produce the list of dictionaries: 添加列表以产生字典列表:
for a, b in zip(list_dict, list_englishmark):
a["englishmark"] = b
print(list_dict)
Output: 输出:
[{'id': 1, 'name': 'mari', 'englishmark': 80}, {'id': 2, 'name': 'Arun', 'englishmark': 54}, {'id': 3, 'name': 'ram', 'englishmark':75}]
[{'id':1,'name':'mari','englishmark':80},{'id':2,'name':'Arun','englishmark':54},{'id': 3,'name':'ram','englishmark':75}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.