Python 匹配键,然后更改嵌套字典的值

Python 匹配键,然后更改嵌套字典的值,python,dictionary,Python,Dictionary,我有两个字典,其中的值包含另一个键值对,如下所示: # 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}} 我希望将dict_1的键和“子键”与dict_2匹配,然后更新dict_1内的值,使dict_1的值变得如下: # Desired output: dict_

我有两个字典,其中的值包含另一个键值对,如下所示:

# 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}}
我希望将dict_1的键和“子键”与dict_2匹配,然后更新dict_1内的值,使dict_1的值变得如下:

# Desired output:
dict_1 = {'01': {'a': 2,  'b': 0, 'c': 3}, '02': {'a': 1,  'b': 2, 'c': 0}}
我知道如何使用常规字典中的值更新嵌套字典,如下所示:

# 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}}
但是我不知道如何对两个嵌套字典执行相同的操作。

只需在
dict\u 1
中的每个字典上使用
update()

>>> 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}}
或相当于:

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