Pybites Logo

Python3.9 - dictionary merge

Level: Beginner (score: 2)

Python 3.9 brought an exciting enhancement to the dict built-in class!

Dictionaries can now be merged with the | operator (PEP 584).

This small change lets us write more compact expressions with dictionaries that are easier to read.

Here's an exercise to let you try | out on dictionaries.

Learner's Task

In this Bite, you will write the function, combine_and_count(), which creates the union of a pair of dictionaries, and returns a dictionary that combines the keys and values of both.

If a key appears in both dictionaries, you should sum their values.

Notice that this last is not what | does with dicts.

If two dictionaries, A and B share a key, the value for that key in A | B is the value found in the second dictionary, B, like this:

>>> fruit = {'apple': 3, 'banana': 2, 'orange': 1}
>>> more_fruit = {'pear': 5, 'orange': 2, 'kiwi': 1}
>>> (fruit | more_fruit)['orange']
2
>>> (more_fruit | fruit)['orange']
1

Because you want combine_and_count(), to combine values, you'll also have to check for duplicate keys and, whenever you find them, combine the values by hand.

Example

>>> fruit = {'apple': 3, 'banana': 2, 'orange': 1}
>>> veggies = {'radish': 5, 'artichoke': 2, 'chard': 1}
>>> combine_and_count(fruit, veggies)
{'apple': 3, 'banana': 2, 'orange': 1, 'radish': 5, 'artichoke': 2, 'chard': 1}
>>> more_fruit = {'pear': 5, 'orange': 2, 'kiwi': 1}
>>> combine_and_count(fruit, more_fruit)  # add the values for 'orange'
{'apple': 3, 'banana': 2, 'orange': 3, 'pear': 5, 'kiwi': 1}

If either dictionary is empty, the function should return the other dictionary:

>>> empty_sack = {}
>>> combine_and_count(fruit, empty_sack)
{'apple': 3, 'banana': 2, 'orange': 1}
>>> combine_and_count(empty_sack, more_fruit)
{'pear': 5, 'orange': 2, 'kiwi': 1}

Keep calm and code in Python!