How to Group a List of Dictionaries by Key in Python

Group a list of dictionaries by a specified key field using dict.setdefault to build a dictionary of lists.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

17 lines
Python 3.9+
def group_by_key(records, key):
    grouped = {}
    for record in records:
        grouped.setdefault(record[key], []).append(record)
    return grouped

if __name__ == "__main__":
    data = [
        {"name": "Alice", "dept": "engineering"},
        {"name": "Bob", "dept": "sales"},
        {"name": "Carol", "dept": "engineering"},
        {"name": "Dave", "dept": "sales"},
        {"name": "Eve", "dept": "engineering"},
    ]
    result = group_by_key(data, "dept")
    for dept, people in result.items():
        print(f"{dept}: {[p['name'] for p in people]}")

Output

stdout
engineering: ['Alice', 'Carol', 'Eve']
sales: ['Bob', 'Dave']

How it works

The group_by_key function iterates over each record and uses setdefault on the grouping key. setdefault(key, []) returns the existing list if the key is present, otherwise inserts an empty list and returns it — so records always append to a valid list. This avoids the common pattern of checking if key in grouped and explicitly initializing the list. The result is a dictionary where each key maps to a list of all dictionaries sharing that key value. This approach is efficient because setdefault performs a single lookup instead of separate get/set operations.

Common mistakes

  • Using `grouped[record[key]].append(record)` without initializing the list first, which raises KeyError
  • Forgetting that the grouping key must exist in every record — missing keys will raise a KeyError
  • Mutating the grouped dictionary while iterating over the source list, which can cause confusing behavior

Variations

  1. Use `collections.defaultdict(list)` to automatically create lists for new keys
  2. Use a dictionary comprehension with `itertools.groupby` if the input is already sorted by the grouping key

Real-world use cases

  • Partitioning API response records by status code to handle successes and failures separately.
  • Grouping log entries by severity level before writing them to distinct output streams.
  • Organizing customer orders by region in a reporting pipeline for per-region analytics.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.