Is there any pythonic way to combine two dicts (adding values fo

ghz 6months ago ⋅ 213 views

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

For example I have two dicts:

Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}

I need a pythonic way of 'combining' two dicts such that the result is:

{'a': 1, 'b': 5, 'c': 7, 'd': 5}

That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.

Answers

To combine two dictionaries in the way you described, you can use dictionary comprehensions and the set operations to handle the keys. Here's a Pythonic way to achieve the desired result:

dict_a = {'a': 1, 'b': 2, 'c': 3}
dict_b = {'b': 3, 'c': 4, 'd': 5}

combined_dict = {key: dict_a.get(key, 0) + dict_b.get(key, 0) for key in set(dict_a) | set(dict_b)}

print(combined_dict)

Explanation:

  1. Set Union: set(dict_a) | set(dict_b) creates a set of all unique keys from both dictionaries.
  2. Dictionary Comprehension: {key: dict_a.get(key, 0) + dict_b.get(key, 0) for key in ...} iterates over each key in the union of keys and sums the values from both dictionaries. If a key is not present in one of the dictionaries, dict.get(key, 0) returns 0.

Example:

dict_a = {'a': 1, 'b': 2, 'c': 3}
dict_b = {'b': 3, 'c': 4, 'd': 5}

combined_dict = {key: dict_a.get(key, 0) + dict_b.get(key, 0) for key in set(dict_a) | set(dict_b)}

print(combined_dict)
# Output: {'a': 1, 'b': 5, 'c': 7, 'd': 5}

Alternative Using collections.defaultdict:

Another approach is to use collections.defaultdict to handle the addition more succinctly:

from collections import defaultdict

dict_a = {'a': 1, 'b': 2, 'c': 3}
dict_b = {'b': 3, 'c': 4, 'd': 5}

combined_dict = defaultdict(int)

for key, value in dict_a.items():
    combined_dict[key] += value

for key, value in dict_b.items():
    combined_dict[key] += value

print(dict(combined_dict))

Explanation:

  1. defaultdict: defaultdict(int) creates a dictionary that returns 0 for any missing key.
  2. Updating Values: Loop through each dictionary and add the values to the defaultdict.

Example:

from collections import defaultdict

dict_a = {'a': 1, 'b': 2, 'c': 3}
dict_b = {'b': 3, 'c': 4, 'd': 5}

combined_dict = defaultdict(int)

for key, value in dict_a.items():
    combined_dict[key] += value

for key, value in dict_b.items():
    combined_dict[key] += value

print(dict(combined_dict))
# Output: {'a': 1, 'b': 5, 'c': 7, 'd': 5}

Both methods are efficient and Pythonic, but the dictionary comprehension approach is more concise. Use the one that fits your preference and coding style.