2013-10-24 176 views
10

鉴于字典的两个列表的两个列表:的Python:合并字典

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

实施merge_lists_of_dicts基于字典项的键是什么字典合并两列什么办法?

+3

如果lst2 [0] = {id:2,x:“five”}或者如果lst2 [0] = {id:2,y:“y”} – alko

+1

如果“id”相同,但值不是?,如果你的字典只有一个项目,为什么不使用元组?我认为你正在使用字典错误? –

+0

你使用python 3吗? – LostAvatar

回答

5

一种可能的方式来定义它:

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

注意,这将让{'id': 2, 'x': 'three'}{'id': 2, 'x': 'two'}因为你没有定义在这种情况下会发生什么。

还要注意的是,看似等价,更有吸引力

set(lst1 + lst2) 

将无法​​工作,因为dict s为没有哈希的。

4
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 

输出

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

您可以copyupdate字典方法做到这一点:

lst3 = lst1.copy() 
lst3.update(lst2) 

# or even, with the addition: 
lst3 = dict(lst1.items() + lst2.items()) 

如果在你的字典重复,将使用第二的价值观。

看看How to merge two Python dictionaries in a single expression?

+0

为什么你要为列表调用复制方法?问题不在于合并字典,而在于列表中的字典。 – apopovych

5

也许最简单的选项

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

这仅保持独特ids在列表中,但不保的顺序。

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