【问题标题】:Merge multiple list of dict with same value in common key [closed]在公共键中合并具有相同值的多个dict列表[关闭]
【发布时间】:2017-11-01 00:36:04
【问题描述】:

我有 4 个字典列表

list1 = [{'a':0,'b':23}, {'a':3,'b':77},{'a':1,'b':99}]

list2 = [{'a':1,'c':666},{'a':4,'c':546}]

list3 = [{'d':33,'a':3},{'d':1111,'a':4},{'d':76,'a':1},{'d':775,'a':0}]

list4 = [{'a':2,'e':12},{'a':4,'e':76}]

列表中的每个 dict 都有一个公共键“a”。我的要求是应该合并所有列表中具有相同值的 dict 中的“a”键,如果合并时 dicts 中不存在特定键,则为这些键分配 0 或忽略这些键。 例如。对于值为 1 的键“a”,从上面的示例中,我们有 2 个字典,一个来自 list1 即 {'a':0,'b':23} 一个是 list3,最后一个 dict 即 {'d':775,' a':0},所以我们首先确定了具有相同'a'值的字典,现在需要合并这些字典 即{'a':0, 'b':23, 'c':0, 'd':775, 'e':0},因为两个dict都没有'c',所以分配了'c'此处为 0

我应该得到如下输出:

[{'a':0,'b':23,'c':0,'d':775, 'e':0},{'a':1,'b':99,'c':666,'d':76,'e':0},{'a':2,'b':0,'c':0,'d':0,'e':12},{'a':3,'b':77,'c':0,'d':33,'e':0}, {'a':4,'b':0,'c':546,'d':1111,'e':76}]

使用最小循环或列表理解

【问题讨论】:

  • 你能解释一下这四个列表应该如何连接的逻辑吗?一个简单的算法步骤列表可能就足够了。也请与我们分享您已经尝试过的任何代码。
  • 所有列表都有一个公共键 'a' 。应该合并所有列表中具有相同值的“a”键。
  • 应该如何处理重复键,即如果a==0在两个字典和两个字典中都存在键b,应该保留哪个值。到目前为止,您尝试过什么?
  • 不会出现重复的键。所有的字典都是唯一的。

标签: python dictionary


【解决方案1】:

如果你想要一个更 Pythonic 的方式:

from itertools import groupby
from pprint import pprint
from collections import ChainMap

a = [{'a':0,'b':23}, {'a':3,'b':77}, {'a':1,'b':99}]
b = [{'a':1,'c':666}, {'a':4,'c':546}]
c = [{'d':33,'a':3}, {'d':1111,'a':4}, {'d':76,'a':1}, {'d':775,'a':0}]
d = [{'a':2,'e':12}, {'a':4,'e':76}]

dict_list = a + b + c + d

# You just need to specify the key you want to use in the lambda function
# There's no need to declare the different key values previously
res = map(lambda dict_tuple: dict(ChainMap(*dict_tuple[1])),
          groupby(sorted(dict_list,
                         key=lambda sub_dict: sub_dict["a"]),
                  key=lambda sub_dict: sub_dict["a"]))

pprint(list(res))

输出:

[{'a': 0, 'b': 23, 'd': 775},
 {'a': 1, 'b': 99, 'c': 666, 'd': 76},
 {'a': 2, 'e': 12},
 {'a': 3, 'b': 77, 'd': 33},
 {'a': 4, 'c': 546, 'd': 1111, 'e': 76}]

编辑(改进):

你也可以使用

from _operator import itemgetter
key=itemgetter("a")

而不是

key=lambda sub_dict: sub_dict["a"]

带有 itemgetter 的版本要快得多。使用您提供的示例:

- Lambda: 0.037109375ms
- Itemgetter: 0.009033203125ms

【讨论】:

  • 我刚刚使用 itemgetter 而不是 lambdas 添加了性能改进。
猜你喜欢
  • 2020-03-12
  • 2019-10-14
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
相关资源
最近更新 更多