简体   繁体   English

如何按键合并多个词典

[英]How to merge multiple dictionaries by key

I want to get an union-like merged dict of multiple (3 or more) dictionaries. 我想得到多个(3个或更多)字典的类似工会的合并字典。

What I have: 我有的:

d1 = {'key1': 'x1', 'key2': 'y1', 'key4': 'z1'}
d2 = {'key1': 'x2', 'key2': 'y2', 'key5': 'z2'}
d3 = {'key1': 'x3', 'key3': 'y3', 'key4': 'z3'}

What I want to get: 我想得到什么:

d_merged = {
    'key1' : ('x1', 'x2', 'x3'),
    'key2' : ('y1', 'y2', None),
    'key3' : (None, None, 'y3'),
    'key4' : ('z1', None, 'z3'), 
    'key5' : (None, 'z2', None)
}

What is the most pythonic / efficient way to to this? 最有效的方法是什么?

I've found an example for 2 dictionaries here , but is there a better way (eg: a comprehension) what can solve the missing key problem for some dictionaries here? 我发现2本字典的例子在这里 ,但有没有更好的方法(例如:一个修真)有什么可以解决缺少关键问题在这里的一些词典?

Is there a way to do the same merge for any number of input dictionaries? 是否可以对任意数量的输入词典进行相同的合并?

Produce a union of all the keys, then iterate over that union to gather values: 产生所有键的并集,然后对该联合进行迭代以收集值:

result = {key: (d1.get(key), d2.get(key), d3.get(key))
          for key in d1.keys() | d2.keys() | d3.keys()}

In Python 3, dict.keys() gives you a dictionary view object , which acts like a set. 在Python 3中, dict.keys()为您提供了一个字典视图对象 ,其作用类似于集合。 You can create a union of all keys in all dictionaries with | 您可以使用|创建所有词典中所有键的并集| on those objects. 在那些对象上。

In Python 2, use dict.viewkeys() instead. 在Python 2中,请改用dict.viewkeys()

Demo: 演示:

>>> d1 = {'key1': 'x1', 'key2': 'y1', 'key4': 'z1'}
>>> d2 = {'key1': 'x2', 'key2': 'y2', 'key5': 'z2'}
>>> d3 = {'key1': 'x3', 'key3': 'y3', 'key4': 'z3'}
>>> {key: (d1.get(key), d2.get(key), d3.get(key))
...  for key in d1.keys() | d2.keys() | d3.keys()}
{'key1': ('x1', 'x2', 'x3'), 'key5': (None, 'z2', None), 'key3': (None, None, 'y3'), 'key4': ('z1', None, 'z3'), 'key2': ('y1', 'y2', None)}
>>> from pprint import pprint
>>> pprint(_)
{'key1': ('x1', 'x2', 'x3'),
 'key2': ('y1', 'y2', None),
 'key3': (None, None, 'y3'),
 'key4': ('z1', None, 'z3'),
 'key5': (None, 'z2', None)}

For an arbitrary sequence of dictionaries, use set().union(*dictionaries) and a tuple() call on a generator expression: 对于任意字典序列 ,请在生成器表达式上使用set().union(*dictionaries)tuple()调用:

dictionaries = (d1, d2, d3)  # or more
result = {key: tuple(d.get(key) for d in dictionaries)
          for key in set().union(*dictionaries)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM