Introduction
Dictionaries are a fundamental data structure in Python, and they are used to store key-value pairs. Sometimes, we may need to combine the values of two or more dictionaries into a single dictionary. In this challenge, you will write a function that takes two or more dictionaries as arguments and returns a new dictionary that combines the values of the input dictionaries.
Combine Dictionary Values
Write a function combine_values(*dicts) that takes two or more dictionaries as arguments and returns a new dictionary that combines the values of the input dictionaries. The function should perform the following steps:
- Create a new
collections.defaultdictwithlistas the default value for each key. - Loop over the input dictionaries and for each dictionary:
- Loop over the keys of the dictionary.
- Append the value of the key to the list of values for that key in the
defaultdict.
- Convert the
defaultdictto a regular dictionary using thedict()function. - Return the resulting dictionary.
The function should have the following signature:
def combine_values(*dicts):
pass
from collections import defaultdict
def combine_values(*dicts):
res = defaultdict(list)
for d in dicts:
for key in d:
res[key].append(d[key])
return dict(res)
d1 = {'a': 1, 'b': 'foo', 'c': 400}
d2 = {'a': 3, 'b': 200, 'd': 400}
combine_values(d1, d2) ## {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}
Summary
In this challenge, you have learned how to combine the values of two or more dictionaries into a single dictionary. You have written a function that takes two or more dictionaries as arguments and returns a new dictionary that combines the values of the input dictionaries.