Python: Combine two or more dictionaries, creating a list of values for each key
68. Combine Dictionaries Creating List of Values per Key
Write a Python program to combine two or more dictionaries, creating a list of values for each key.
- Create a new collections.defaultdict with list as the default value for each key and loop over dicts.
- Use dict.append() to map the values of the dictionary to keys.
- Use dict() to convert the collections.defaultdict to a regular dictionary.
Sample Solution:
Python Code:
Sample Output:
Original dictionaries: {'w': 50, 'x': 100, 'y': 'Green', 'z': 400} {'x': 300, 'y': 'Red', 'z': 600} Combined dictionaries, creating a list of values for each key: {'w': [50], 'x': [100, 300], 'y': ['Green', 'Red'], 'z': [400, 600]}
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Python program to merge two dictionaries so that each key maps to a list of values from both dictionaries using defaultdict.
- Write a Python program to combine multiple dictionaries into one by appending values for duplicate keys into lists.
- Write a Python program to iterate over multiple dictionaries and construct a new dictionary where each key’s value is a list of all corresponding values.
- Write a Python program to implement a function that takes several dictionaries and returns a combined dictionary with keys mapping to lists of values.
Go to:
Previous: Write a Python program to invert a given dictionary with non-unique hashable values.
Next: Write a Python program to group the elements of a given list based on the given function.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.