简体   繁体   English

如何在python中组合字典

[英]How to combine the dictionaries in python

I have 2 dictionaries 我有2本词典

dict1 = {'color': {'attri': ['Black']}, 'diameter': {'attri': ['(300, 600)']}}

dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}}

I want to combine the 2 dictionaries such that 我想结合这两个词典

dict3 = {'color': {'op': 'in', 'attri': ['Black']}, 'diameter': {'op': 'range', 'attri': ['(300,600)']}}

This method uses a defaultdict and is safe even if a key only appears in one of the dictionaries. 此方法使用defaultdict ,即使密钥只出现在其中一个字典中,也是安全的。

import itertools
import collections

dict3 = collections.defaultdict(dict)

for key, value in itertools.chain(dict1.items(), dict2.items()):
     dict3[key].update(value)

Proof -- applied to: 证明 - 适用于:

dict1 = {'color': {'attri':['Black']}, 'diameter': {'attri':['(300, 600)']}}
dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}}

the output of dict(dict3) is: dict(dict3)的输出是:

{'color': {'attri': ['Black'], 'op': 'in'},
'diameter': {'attri': ['(300, 600)'], 'op': 'range'},
'size': {'op': 'in'}}

Although looking at your expected output, you only want a result if the key appears in both dictionaries, in which case I'd do: 虽然查看了您的预期输出,但如果密钥出现在两个字典中,您只需要一个结果,在这种情况下,我会这样做:

for key in set(itertools.chain(dict1, dict2)):
    if key in dict1 and key in dict2:
         dict3[key] = {**dict1, **dict2}

Just use a mix of dict comprehensions and dict unpacking : 只需使用dict comprehensionsdict unpacking的混合:

dict1 = {'color': {'attri':['Black']}, 'diameter': {'attri':['(300, 600)']}}
dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}}

dict3 = {n:{**dict1[n],**dict2[n]} for n in dict1}
res = {}
for item in dict1:
  res.setdefault(item, {})
  res[item].update(dict1[item])
  if item in dict2:
    res[item].update(dict2[item])

For dictionaries x and y, z becomes a merged dictionary with values from y and from x. 对于字典x和y,z成为合并字典,其值来自y和x。

In Python 3.5 or greater, : 在Python 3.5或更高版本中,:

z = {**x, **y}

In Python 2, (or 3.4 or lower) write a function: 在Python 2中,(或3.4或更低版本)编写一个函数:

def merge_two_dicts(x, y):
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z
and

z = merge_two_dicts(x, y)

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

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