Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two dictionaries without clobbering

Tags:

python

I have two dictionaries and I want to combine them.

dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}

I want to end up with

{'abc': {'test1': 123, 'test2': 456}}

if dict2 = {'abc': 100} then I would want:

{'abc' 100}

I tried dict1.update(dict2) but that gave me {'abc': {'test2': 456}}

Is there a pythonic way to do this?

like image 244
Daniel Huckson Avatar asked Oct 12 '25 12:10

Daniel Huckson


1 Answers

IIUC, you could do the following:

def recursive_update(d1, d2):
    """Updates recursively the dictionary values of d1"""

    for key, value in d2.items():
        if key in d1 and isinstance(d1[key], dict) and isinstance(value, dict):
            recursive_update(d1[key], value)
        else:
            d1[key] = value


dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}

recursive_update(dict1, dict2)

print(dict1)

Output

{'abc': {'test1': 123, 'test2': 456}}

Note that the recursion only works for values that are dictionaries. For example:

dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': 100}

produces (as expected):

{'abc': 100}
like image 159
Dani Mesejo Avatar answered Oct 16 '25 11:10

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!