如何将值列表添加到嵌套字典列表中?

时间:2020-10-12 09:38:33

标签: python list loops dictionary nested

我想使用新的键名将列表的每个值添加到不同列表的每个嵌套字典中。

词典列表:

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]

列表:

list = ['en', 'nl']

所需的输出:

list_dicts = [{'id': 1, 'text': 'abc', 'language': 'en'}, {{'id':2, 'text': 'def', 'language':'nl'}]

当前使用的方法: 我将list_dicts转换为Pandas数据框,并添加了一个新列'language'来表示list值。然后,我使用df.to_dict('records')将Pandas数据框转换回字典列表。必须有一种更有效的方法来遍历列表,并将每个值添加到词典列表中新分配的键上,而根本不需要使用Pandas。有什么想法吗?

6 个答案:

答案 0 :(得分:1)

zip中使用列表理解

例如:

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
lst = ['en', 'nl']

list_dicts = [{**n, "language": m} for n,m in zip(list_dicts, lst)]
print(list_dicts)
# --> [{'id': 1, 'text': 'abc', 'language': 'en'}, {'id': 2, 'text': 'def', 'language': 'nl'}]

答案 1 :(得分:1)

一个简单的压缩列表循环就可以了:

for d, lang in zip(list_dicts, list):
    d["language"] = lang

旁注:您不应命名变量list,以免隐藏内置名称。

答案 2 :(得分:1)

尝试这样(不要使用list作为变量名):

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
langlist = ['en', 'nl']
x = 0
for y in list_dicts:
  y['language'] = langlist[x]
  x=x+1

print(list_dicts)

答案 3 :(得分:1)

list = ['en', 'nl']   # Don't use list as variable name tho.
list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]


for i,item in enumerate(list):
    list_dicts[i]['language'] = item

如果您只想为“语​​言”键分配值,那应该可以解决问题。

答案 4 :(得分:1)

简单地:

for d, l in zip(list_dicts, list):
    d['language'] = l

然后:

print(list_dicts)

答案 5 :(得分:1)

(假设两个列表的长度相同)

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]

list_lang = ['en', 'nl'] 

for i in range(len(list_dicts)):
    list_dicts[i]['language']=list_lang[i]

>>> print(list_dicts)
[{'id': 1, 'text': 'abc', 'language': 'en'}, {'id': 2, 'text': 'def', 'language': 'nl'}]