Python: Grouping a sequence of key-value pairs into a dictionary of lists using collections module
Python Collections: Exercise-28 with Solution
Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. Use collections module.
Sample Solution:
Python Code:
from collections import defaultdict
def grouping_dictionary(l):
d = defaultdict(list)
for k, v in l:
d[k].append(v)
return d
colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
print("Original list:")
print(colors)
print("\nGrouping a sequence of key-value pairs into a dictionary of lists:")
print(grouping_dictionary(colors))
Sample Output:
Original list: [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] Grouping a sequence of key-value pairs into a dictionary of lists: defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
Flowchart:
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to remove duplicate words from a given string use collections module.
Next: Write a Python program to get the frequency of the elements in a given list of lists. Use collections module.
What is the difficulty level of this exercise?
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Inverts a dictionary with unique hashable values:
Example:
def tips_invert_dictionary(obj): return { value: key for key, value in obj.items() } ages = { "Owen": 29, "Eddie": 15, "Jhon": 22, } print(tips_invert_dictionary(ages))
Output:
{29: 'Owen', 15: 'Eddie', 22: 'Jhon'}
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework