如何将列表作为新项目加入列表字典-python?

时间:2019-04-12 08:30:35

标签: python list dictionary

也许是一个简单的问题:

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

我不确定在这里使用正确的代码吗?

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

答案 2 :(得分:2)

类似的事情可能会起作用

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

编辑: 如@Netwave所述,您应确保len(list_age)不大于len(list_dict)

答案 3 :(得分:0)

添加列表以生成词典列表:

for a, b in zip(list_dict, list_englishmark):
    a["englishmark"] = b

print(list_dict)

输出:

  

[{'id':1,'name':'mari','englishmark':80},{'id':2,'name':'Arun','englishmark':54},{' id':3,'name':'ram','englishmark':75}]

相关问题