Python:合并两个词典列表

xia*_*012 17 python merge dictionary list

给出两个词典列表:

>>> 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"}]
Run Code Online (Sandbox Code Playgroud)

有没有merge_lists_of_dicts什么方法可以实现基于字典项的键合并两个字典列表?

the*_*eye 14

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
Run Code Online (Sandbox Code Playgroud)

输出

[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]
Run Code Online (Sandbox Code Playgroud)

  • 这个应该被宣布为答案,为什么六年后问题的作者没有投票支持这个? (2认同)

geo*_*org 11

也许是最简单的选择

result = {x['id']:x for x in lst1 + lst2}.values()
Run Code Online (Sandbox Code Playgroud)

ids在列表中仅保留唯一,但不保留订单.

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

  • @KimStacks,您可以通过执行以下操作将其转换为列表:`list(result)` (2认同)

roi*_*ppi 6

一种可能的定义方式:

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'}]
Run Code Online (Sandbox Code Playgroud)

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

还要注意看似等效且更具吸引力的

set(lst1 + lst2)
Run Code Online (Sandbox Code Playgroud)

不会工作,因为dicts不可清洗.