PYTHON

Grouping a List of Dictionaries by a Common Key

Learn to efficiently group a list of dictionaries by a specific key's value using `collections.defaultdict` in Python, perfect for organizing fetched data in web development.

from collections import defaultdict

def group_by_key(data_list, key_name):
    """
    Groups a list of dictionaries by the value of a specified key.
    Returns a dictionary where keys are the unique values of key_name,
    and values are lists of dictionaries that share that key_name value.
    """
    grouped_data = defaultdict(list)
    for item in data_list:
        key_value = item.get(key_name)
        if key_value is not None: # Only group if key exists and has a value
            grouped_data[key_value].append(item)
    return dict(grouped_data) # Convert defaultdict back to a regular dict

# Example Usage:
users_data = [
    {"id": 1, "name": "Alice", "city": "New York"},
    {"id": 2, "name": "Bob", "city": "London"},
    {"id": 3, "name": "Charlie", "city": "New York"},
    {"id": 4, "name": "David", "city": "Paris"},
    {"id": 5, "name": "Eve", "city": "London"},
]

# Group users by city
users_by_city = group_by_key(users_data, "city")
print(f"Users grouped by city: {users_by_city}")

products_data = [
    {"id": "A1", "name": "Laptop", "category": "Electronics"},
    {"id": "B2", "name": "Keyboard", "category": "Electronics"},
    {"id": "C3", "name": "T-Shirt", "category": "Apparel"},
    {"id": "D4", "name": "Mouse", "category": "Electronics"},
]

# Group products by category
products_by_category = group_by_key(products_data, "category")
print(f"Products grouped by category: {products_by_category}")
How it works: This Python snippet demonstrates how to group a list of dictionaries based on the value of a specific key. It uses `collections.defaultdict(list)`, which automatically creates an empty list for a key if it doesn't exist, simplifying the grouping logic. The function iterates through each dictionary, extracts the value of the specified `key_name`, and appends the entire dictionary to the corresponding list in the `defaultdict`. This pattern is incredibly useful for structuring data fetched from APIs or databases for display or further processing in web applications, such as organizing users by region or products by category.

Need help integrating this into your project?

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

Hire DigitalCodeLabs