也许是一个简单的问题:
在 python 中,我有一个字典列表,我想在列表中的每个字典中添加一个列表作为新项目?
例如我有字典列表:
list_dict =[{'id':1, 'text':'John'},
{'id':2, 'text':'Amy'},
{'id':3, 'text':'Ron'}]
还有一个列表:
list_age = [23, 54, 41]
然后我如何添加列表以生成字典列表:
list_dict =[{'id':1, 'text':'John', 'age':23},
{'id':2, 'text':'Amy', 'age':54},
{'id':3, 'text':'Ron', 'age':41}]
我不确定在这里使用正确的代码?
请您参考如下方法:
使用 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}]
