Group key-value pairs into lists

EasyDictionary Programs · 57 of 94

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

Advertisement
Input
[("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]
Output
{'virat': [50, 30], 'rohit': [40, 10]}

Approach

  1. defaultdict(list).

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs