Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine the dictionaries in python

Tags:

python

django

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)']}}
like image 797
Aakash Patel Avatar asked Dec 10 '22 06:12

Aakash Patel


2 Answers

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()}
like image 109
FHTMitchell Avatar answered Dec 20 '22 07:12

FHTMitchell


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}
like image 31
MegaIng Avatar answered Dec 20 '22 08:12

MegaIng