Python:合并两个词典列表

时间:2013-10-24 09:13:12

标签: python list dictionary merge

给出两个词典列表:

>>> 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的方法是什么根据字典项的键合并两个字典列表?

5 个答案:

答案 0 :(得分:10)

也许是最简单的选择

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

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

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

答案 1 :(得分: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'}]

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

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

set(lst1 + lst2)

不起作用,因为dict不可用。

答案 2 :(得分: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}]

答案 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?

答案 4 :(得分:0)

顺便说一句,您可以使用“ pandas”进行此类计算:

>>> import pandas as pd
>>> 
>>> lst1 = [{"id": 1, "x": "one"}, {"id": 2, "x": "two"}]
>>> lst2 = [{"id": 2, "x": "two"}, {"id": 3, "x": "three"}]
>>> 
>>> lst1_df = pd.DataFrame(lst1)
>>> lst2_df = pd.DataFrame(lst2)
>>> lst_concat_df = pd.concat([lst1_df, lst2_df])
>>> lst_grouped_res_df = lst_concat_df.groupby(["id", "x"]).agg(sum)
>>> print(lst_grouped_res_df.reset_index().to_dict('records'))

输出:

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

相关问题