25

给定两个字典列表:

>>> 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基于字典项的键合并两个字典列表的方法?

4

4 回答 4

17

也许是最简单的选择

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

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

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

于 2013-10-24T09:32:01.957 回答
16
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}]
于 2013-10-24T09:29:28.070 回答
10

定义它的一种可能方法:

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)

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

于 2013-10-24T09:28:04.680 回答
3

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

>>> 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': '一'}, {'id': 2, 'x': '二'}, {'id': 3, 'x': '三'}]

于 2020-11-16T16:40:21.447 回答