Python Practice › Tuple Programs › Program 25
Group a list of pairs into a dictionary
Write a Python program to group (key, value) tuples into a dictionary of lists.
Input
[("s", 2), ("q", 1), ("a", 1), ("s", 3), ("q", 2), ("a", 4)]Output
{'s': [2, 3], 'q': [1, 2], 'a': [1, 4]}Approach
setdefault(key, [])creates the list on first use.
Solution
data = [("s", 2), ("q", 1), ("a", 1), ("s", 3), ("q", 2), ("a", 4)]result = {}for key, value in data: result.setdefault(key, []).append(value)print(result)Output
{'s': [2, 3], 'q': [1, 2], 'a': [1, 4]}Learn the concept
New to this topic? Read the lesson, then come back.