Python Practice › Dictionary Programs › Program 57
Group key-value pairs into lists
Write a Python program to group a sequence of (key, value) pairs into a dictionary of lists.
Input
[("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]Output
{'virat': [50, 30], 'rohit': [40, 10]}Approach
defaultdict(list).
Solution
from collections import defaultdict pairs = [("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]groups = defaultdict(list)for k, v in pairs: groups[k].append(v)print(dict(groups))Output
{'virat': [50, 30], 'rohit': [40, 10]}Note
A dict literal cannot hold the same key twice, so the input is a list of pairs.
Learn the concept
New to this topic? Read the lesson, then come back.