avatar Bite 371. Python3.9 - Dictionary Merge

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!

Login and get coding
go back Beginner level
Bitecoin 2X

25 out of 25 users completed this Bite.
Will you be the 26th person to crack this Bite?
Resolution time: ~42 min. (avg. submissions of 5-240 min.)
Our community rates this Bite 5.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help