Group equal items
Write a Python program to group equal items of a list into dictionary values.
[1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4], 5: [5, 5, 5]}Approach
setdefault(x, []).append(x), then sort by key.
Solution
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()))){1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4], 5: [5, 5, 5]}Learn the concept
New to this topic? Read the lesson, then come back.