Python Practice › Dictionary Programs › Program 77
Group a list by a function
Write a Python program to group the elements of a list by the result of a function such as len.
Input
["abc", "defg", "hijkl"]
Output
{3: ['abc'], 4: ['defg'], 5: ['hijkl']}
{'odd': [1, 3, 5], 'even': [2, 4]}Approach
defaultdict(list)keyed byfunc(item).
Solution
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.