PYTHON

Group List Items by a Specific Key

Efficiently group a list of dictionaries or objects by a common key or attribute using `collections.defaultdict`, perfect for organizing structured data from databases or APIs.

from collections import defaultdict

data = [
    {'id': 1, 'category': 'fruit', 'name': 'apple'},
    {'id': 2, 'category': 'vegetable', 'name': 'carrot'},
    {'id': 3, 'category': 'fruit', 'name': 'banana'},
    {'id': 4, 'category': 'vegetable', 'name': 'broccoli'},
]

grouped_data = defaultdict(list)
for item in data:
    group_key = item['category']
    grouped_data[group_key].append(item)

# Result (defaultdict converts to dict on print):
# {
#  'fruit': [
#   {'id': 1, 'category': 'fruit', 'name': 'apple'},
#   {'id': 3, 'category': 'fruit', 'name': 'banana'}
#  ],
#  'vegetable': [
#   {'id': 2, 'category': 'vegetable', 'name': 'carrot'},
#   {'id': 4, 'category': 'vegetable', 'name': 'broccoli'}
#  ]
# }
How it works: This snippet utilizes `collections.defaultdict` to group items from a list of dictionaries based on a common key ('category' in this example). By initializing `defaultdict(list)`, any time a new key is accessed in `grouped_data`, an empty list is automatically created for it, allowing you to directly append items without first checking if the key exists. This simplifies data aggregation and organization.

Need help integrating this into your project?

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

Hire DigitalCodeLabs