I have 2 dictionaries
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.
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:
{'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:
dict3 = {key: {**dict1[key], **dict2[key]}
for key in dict1.keys() & dict2.keys()}
Just use a mix of dict comprehensions
and dict 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With