There are multiple ways to achieve that but my favorite is the following:
dict_1 = {'a': 10, 'b': 20, 'c': 30} dict_2 = {'c': 40, 'd': 50, 'e': 60} merged_dict = {dict_key: dict_1.get(dict_key, 0) + dict_2.get(dict_key, 0) for dict_key in set(dict_1) | set(dict_2)} assert merged_dict == {'a': 10, 'b': 20, 'c': 70,'d': 50, 'e': 60}
But with this structure you can do more things like merge only the entries defined in one of dictionaries:
merged_dict_1 = {dict_key: dict_1.get(dict_key, 0) + dict_2.get(dict_key, 0) for dict_key in set(dict_1)} assert merged_dict_1 == {'a': 10, 'b': 20, 'c': 70}
Or keep only the common entries:
common_dict = {dict_key: dict_1.get(dict_key, 0) + dict_2.get(dict_key, 0) for dict_key in set(dict_1) & set(dict_2)} assert common_dict == {'c': 70}