Python:合并两个字典列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19561707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:03:53  来源:igfitidea点击:

Python: Merge two lists of dictionaries

pythonlistdictionarymerge

提问by xiaohan2012

Given two lists of dictionaries:

给定两个字典列表:

>>> lst1 = [{id: 1, x: "one"},{id: 2, x: "two"}]
>>> lst2 = [{id: 2, x: "two"}, {id: 3, x: "three"}]
>>> merge_lists_of_dicts(lst1, lst2) #merge two lists of dictionary items by the "id" key
[{id: 1, x: "one"}, {id: 2, x: "two"}, {id: 3, x: "three"}]

Any way to implement merge_lists_of_dictswhat merges two lists of dictionary based on the dictionary items' keys?

merge_lists_of_dicts什么方法可以根据字典项的键来实现合并两个字典列表的内容吗?

回答by roippi

One possible way to define it:

一种可能的定义方式:

lst1 + [x for x in lst2 if x not in lst1]
Out[24]: [{'id': 1, 'x': 'one'}, {'id': 2, 'x': 'two'}, {'id': 3, 'x': 'three'}]

Note that this will keep both{'id': 2, 'x': 'three'}and {'id': 2, 'x': 'two'}as you did not define what should happen in that case.

请注意,这将保留两者{'id': 2, 'x': 'three'}{'id': 2, 'x': 'two'}因为您没有定义在这种情况下应该发生什么。

Also note that the seemingly-equivalent and more appealing

另请注意,看似等效且更具吸引力的

set(lst1 + lst2)

will NOT work since dicts are not hashable.

将不起作用,因为dicts 不可散列。

回答by thefourtheye

lst1 = [{"id": 1, "x": "one"}, {"id": 2, "x": "two"}]
lst2 = [{"id": 2, "x": "two"}, {"id": 3, "x": "three"}]

result = []
lst1.extend(lst2)
for myDict in lst1:
    if myDict not in result:
        result.append(myDict)
print result

Output

输出

[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]

回答by georg

Perhaps the simplest option

也许是最简单的选择

result = {x['id']:x for x in lst1 + lst2}.values()

This keeps only unique idsin the list, not preserving the order though.

这仅ids在列表中保持唯一,但不保留顺序。

If the lists are really big, a more realistic solution would be to sort them by idand merge iteratively.

如果列表真的很大,更现实的解决方案是对它们进行排序id并迭代合并。