Group equal items

EasyDictionary Programs · 27 of 94

Write a Python program to group equal items of a list into dictionary values.

Advertisement
Input
[1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Output
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4], 5: [5, 5, 5]}

Approach

  1. setdefault(x, []).append(x), then sort by key.

Solution

Python
items = [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]groups = {}for x in items:    groups.setdefault(x, []).append(x)print(dict(sorted(groups.items())))
Output
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4], 5: [5, 5, 5]}
Advertisement

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs