Group a list by a function

EasyDictionary Programs · 77 of 94

Write a Python program to group the elements of a list by the result of a function such as len.

Advertisement
Input
["abc", "defg", "hijkl"]
Output
{3: ['abc'], 4: ['defg'], 5: ['hijkl']}
{'odd': [1, 3, 5], 'even': [2, 4]}

Approach

  1. defaultdict(list) keyed by func(item).

Solution

Python
from collections import defaultdict def group_by(items, func):    groups = defaultdict(list)    for x in items:        groups[func(x)].append(x)    return dict(groups) print(group_by(["abc", "defg", "hijkl"], len))print(group_by([1, 2, 3, 4, 5], lambda n: "even" if n % 2 == 0 else "odd"))
Output
{3: ['abc'], 4: ['defg'], 5: ['hijkl']}
{'odd': [1, 3, 5], 'even': [2, 4]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs