Aaron Bandelli Aaron Bandelli - 14 days ago 5
Python Question

Merging dictionaries of dictionaries

I'd like to know what be the best/most pythonic way to combine two dictionaries of dictionaries.

I have two dictionaries that look like so:

original = {'user1': {'COL': 'green', 'ID': '234235', 'NAME': 'andy'},
'user2': {'COL': 'blue', 'ID': '234234', 'NAME': 'john'}}

update = {'user1': {'COL': 'black', 'ID': '234235', 'NAME': 'andy'},
'user2': {'COL': 'purple', 'SPEC': 'na'}}


I would like to merge them together so that values found in the
update
dictionary would update the respective values in the
original
dictionary.

result = {'user1': {'COL': 'black', 'ID': '234235', 'NAME': 'andy'},
'user2': {'COL': 'purple', 'ID': '234234', 'NAME': 'john', 'SPEC': 'na'}}


I have tried using
collections
and
copy
, however, I end up replacing the entire value for the key.

wim wim
Answer

That is just a simple for-loop:

for k in original:
    original[k].update(update.get(k, {}))
Comments