Python Practice › Tuple Programs › Program 25

Group a list of pairs into a dictionary

EasyTuple Programs · 25 of 70

Write a Python program to group (key, value) tuples into a dictionary of lists.

Advertisement
Input
[("s", 2), ("q", 1), ("a", 1), ("s", 3), ("q", 2), ("a", 4)]
Output
{'s': [2, 3], 'q': [1, 2], 'a': [1, 4]}

Approach

  1. setdefault(key, []) creates the list on first use.

Solution

Python
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]}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs