【问题标题】:Python: Merge two lists of dictionariesPython:合并两个字典列表
【发布时间】:2013-11-02 21:51:54
【问题描述】:

给定两个字典列表:

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

【问题讨论】:

  • 如果 lst2[0] = {id: 2, x: "five"} 或 lst2[0] = {id: 2, y: "y"} 会怎样
  • 如果“id”相同但值不同怎么办?,如果您的字典只有一项,为什么不使用元组?我认为你用错了字典?
  • 你在用python 3吗?
  • 所以,这根本不是重复的。两者是非常显着和重要的不同。
  • @InbarRose 这不是重复的。它正在合并 n 个字典的列表,而另一个正在合并 2 个字典。

标签: python list dictionary merge


【解决方案1】:

也许是最简单的选择

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

这只会在列表中保留唯一的ids,但不会保留顺序。

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

【讨论】:

  • 这将在 python 3 中返回一个dict_values。这与所需的结果略有不同,它是一个普通的字典列表
  • @KimStacks 您可以通过以下方式将其转换为列表:list(result)
【解决方案2】:
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}]

【讨论】:

  • 这个应该被宣布为答案,为什么6年后问题的作者没有投票给这个?
【解决方案3】:

一种可能的定义方式:

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

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

还请注意,看似等效且更吸引人

set(lst1 + lst2)

由于dicts 不可散列,因此无法使用。

【讨论】:

  • 这是所有答案中最正确的,因为这将在 python3 中返回一个列表作为输出
【解决方案4】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    相关资源
    最近更新 更多