PYTHON

Dynamic Multi-Level Object Grouping with Dictionaries

Group complex data (list of dictionaries/objects) into nested dictionaries based on multiple dynamic criteria, perfect for organizing report data or UI elements in Python.

def group_by_keys(data, keys):
    grouped_data = {}
    for item in data:
        current_level = grouped_data
        for i, key in enumerate(keys):
            value = item.get(key) # Use .get() for safety or handle AttributeError for objects
            if i == len(keys) - 1:
                # Last key, append item to a list
                if value not in current_level:
                    current_level[value] = []
                current_level[value].append(item)
            else:
                # Not the last key, create nested dictionary if it doesn't exist
                if value not in current_level:
                    current_level[value] = {}
                current_level = current_level[value]
    return grouped_data

# Example Data (e.g., from a database query or API call)
products = [
    {"category": "Electronics", "brand": "Sony", "model": "XBR", "price": 1200},
    {"category": "Electronics", "brand": "Samsung", "model": "QLED", "price": 1500},
    {"category": "Clothing", "brand": "Nike", "model": "Air Max", "price": 120},
    {"category": "Electronics", "brand": "Sony", "model": "PS5", "price": 500},
    {"category": "Clothing", "brand": "Adidas", "model": "Ultraboost", "price": 180}
]

# Group by 'category' then by 'brand'
grouped_products = group_by_keys(products, ['category', 'brand'])

import json
print(json.dumps(grouped_products, indent=2))
# Expected Output (formatted):
# {
#   "Electronics": {
#     "Sony": [
#       {
#         "category": "Electronics",
#         "brand": "Sony",
#         "model": "XBR",
#         "price": 1200
#       },
#       {
#         "category": "Electronics",
#         "brand": "Sony",
#         "model": "PS5",
#         "price": 500
#       }
#     ],
#     "Samsung": [
#       {
#         "category": "Electronics",
#         "brand": "Samsung",
#         "model": "QLED",
#         "price": 1500
#       }
#     ]
#   },
#   "Clothing": {
#     "Nike": [
#       {
#         "category": "Clothing",
#         "brand": "Nike",
#         "model": "Air Max",
#         "price": 120
#       }
#     ],
#     "Adidas": [
#       {
#         "category": "Clothing",
#         "brand": "Adidas",
#         "model": "Ultraboost",
#         "price": 180
#       }
#     ]
#   }
# }
How it works: This snippet provides a robust function for dynamically grouping a list of dictionaries (or objects) into a multi-level nested dictionary structure based on a sequence of specified keys. Unlike single-level grouping or those requiring pre-sorted data, this utility iterates through each item and builds the nested dictionary structure on-the-fly. This pattern is incredibly useful in web development for organizing complex data for reporting, displaying categorized information in UIs, or preparing data for API responses, allowing flexible data aggregation without manual nesting logic for each scenario.

Need help integrating this into your project?

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

Hire DigitalCodeLabs