如何将列表作为一个新项加入到列表字典中?

2024-04-24 05:10:15 发布

您现在位置:Python中文网/ 问答频道 /正文

也许一个简单的问题:

在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}]

我不确定这里使用的代码是否正确?你知道吗


Tags: 代码textid列表age字典johndict
3条回答

像这样的事情可能有用

for index, item in enumerate(list_age):
  list_dict[index]['age'] = item

编辑: 正如@Netwave提到的,您应该确保len(list_age)不大于len(list_dict)。你知道吗

如果list_agelist_dict长度相同,请尝试此循环:

for i, j in zip(list_dict, list_age):
  i['age']=j

输出

[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]

使用zip迭代匹配对并更新dict:

>>> 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}]

相关问题 更多 >