PYTHON

Grouping Data by a Key Using `itertools.groupby` in Python

Learn to efficiently group consecutive identical elements in a sorted iterable using Python's `itertools.groupby` for powerful data aggregation and processing.

import itertools

# Example data: a list of dictionaries
# IMPORTANT: For itertools.groupby, the iterable must be sorted by the key you want to group by.
people_data = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 30, 'city': 'New York'},
    {'name': 'David', 'age': 25, 'city': 'Los Angeles'},
    {'name': 'Eve', 'age': 30, 'city': 'Boston'}
]

# Sort the data by 'age' to prepare for groupby
sorted_people = sorted(people_data, key=lambda p: p['age'])

print("
Grouping by age:")
for age, group in itertools.groupby(sorted_people, key=lambda p: p['age']):
    print(f"Age: {age}")
    for person in group:
        print(f"  - {person['name']} ({person['city']})")
# Output:
# Grouping by age:
# Age: 25
#   - Bob (Los Angeles)
#   - David (Los Angeles)
# Age: 30
#   - Alice (New York)
#   - Charlie (New York)
#   - Eve (Boston)

# Another example: Grouping strings by their first letter
words = ['apple', 'apricot', 'banana', 'berry', 'cat', 'dog', 'elephant']
# Sort the words alphabetically
sorted_words = sorted(words)

print("
Grouping words by first letter:")
for letter, group in itertools.groupby(sorted_words, key=lambda w: w[0]):
    print(f"Letter: {letter}")
    for word in group:
        print(f"  - {word}")
# Output:
# Grouping words by first letter:
# Letter: a
#   - apple
#   - apricot
# Letter: b
#   - banana
#   - berry
# Letter: c
#   - cat
# Letter: d
#   - dog
# Letter: e
#   - elephant
How it works: The `itertools.groupby` function is a powerful tool for grouping consecutive identical elements in an iterable. Crucially, `groupby` only groups *consecutive* elements that share the same key. Therefore, the iterable *must be sorted* by the key you intend to group by beforehand. It returns an iterator that yields pairs of (key, group), where `key` is the grouping key, and `group` is an iterator yielding all elements that share that key. This makes it highly memory-efficient for large datasets as it processes items sequentially without loading all groups into memory simultaneously.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs