def update_dict_cascade(dict_1, dict_2): """ Update dict_1 with dict_2 in a cascade manner. :param dict_1: The dict to be updated. :param dict_2: The dict used for updating. :return: The updated dict_1. """ if dict_1 == dict_2: pass else: for k, v in dict_2.items(): try: v1 = dict_1[k] if not isinstance(v1, dict) or not isinstance(v, dict): dict_1[k] = [v1, v] else: dict_1[k] = update_dict_cascade(v1, v) except KeyError: dict_1[k] = v return dict_1
Test:
a = {'a': {'aa': {'aaa': 1}}} b = {'a': {'aa': {'bbb': 2}}} c = {'a': {'bb': {'ccc': 3}}} d = {'b': {'bb': {'ddd': 4}}} e = {'c': {'cc': {'eee': 5}}} print(a) update_dict_cascade(a, b) print(a) update_dict_cascade(a, c) print(a) update_dict_cascade(a, d) print(a) update_dict_cascade(a, e) print(a) Output: {'a': {'aa': {'aaa': 1}}} {'a': {'aa': {'aaa': 1, 'bbb': 2}}} {'a': {'aa': {'aaa': 1, 'bbb': 2}, 'bb': {'ccc': 3}}} {'a': {'aa': {'aaa': 1, 'bbb': 2}, 'bb': {'ccc': 3}}, 'b': {'bb': {'ddd': 4}}} {'a': {'aa': {'aaa': 1, 'bbb': 2}, 'bb': {'ccc': 3}}, 'b': {'bb': {'ddd': 4}}, 'c': {'cc': {'eee': 5}}}