Matching keys then changing the values of nested dictionaries

I have two dictionaries which values contain another key-value pairs like so:

# Input:
dict_1 = {'01': {'a': 0,  'b': 0, 'c': 0}, '02': {'a': 0,  'b': 0, 'c': 0}}
dict_2 = {'01': {'a': 2, 'c': 3}, '02': {'a': 1,  'b': 2}}

I wish to match the key and "sub-key" of dict_1 with dict_2 then update the value inside dict_1 so that the values of dict_1 become like so:

# Desired output:
dict_1 = {'01': {'a': 2,  'b': 0, 'c': 3}, '02': {'a': 1,  'b': 2, 'c': 0}}

I know how to update a nested dictionary with values from a regular dictionary like so:

# Input:
dic_tf = {"12345": {"a": 2, "b": 4, "c": 3, "d": 5}, "67891": {"c": 5, "d": 4, "e": 2, "f": 1}}
dic_df = {"a": 10, "b": 20, "c": 30, "d": 40, "e": 50, "f": 60, "g": 70, "h": 80}

for key, val in dic_tf.items():
    val.update((k, dic_df[k]) for k in val.keys() & dic_df.keys())

# Output:
dic_tf = {'12345': {'a': 10, 'b': 20, 'c': 30, 'd': 40}, '67891': {'c': 30, 'd': 40, 'e': 50, 'f': 60}}

But I have no idea how to do the same for two nested dictionaries.

Upvotes: 0

Views: 199

Answers (1)

Samwise
Samwise

Reputation: 71454

Just use update() on each dictionary in dict_1:

>>> dict_1 = {'01': {'a': 0,  'b': 0, 'c': 0}, '02': {'a': 0,  'b': 0, 'c': 0}}
>>> dict_2 = {'01': {'a': 2, 'c': 3}, '02': {'a': 1,  'b': 2}}
>>> for k, v in dict_1.items():
...     v.update(dict_2[k])
...
>>> dict_1
{'01': {'a': 2, 'b': 0, 'c': 3}, '02': {'a': 1, 'b': 2, 'c': 0}}

or equivalently:

>>> for k in dict_1:
...     dict_1[k].update(dict_2[k])
...

Upvotes: 1

Related Questions