PYTHON

Efficiently Filter and Transform a List of Dictionaries

Learn to use Python list comprehensions to efficiently filter and transform a list of dictionaries based on specific criteria, ideal for API response processing.

data = [
    {'id': 1, 'name': 'Alice', 'status': 'active', 'age': 30},
    {'id': 2, 'name': 'Bob', 'status': 'inactive', 'age': 24},
    {'id': 3, 'name': 'Charlie', 'status': 'active', 'age': 35},
    {'id': 4, 'name': 'David', 'status': 'active', 'age': 29}
]

# Filter for active users older than 25 and extract specific fields
active_senior_users = [
    {'id': user['id'], 'name': user['name']}
    for user in data
    if user['status'] == 'active' and user['age'] > 25
]

print(active_senior_users)
How it works: This snippet demonstrates filtering and transforming a list of dictionaries using a single list comprehension. It iterates through the `data` list, selects dictionaries where the `status` is 'active' and `age` is greater than 25, and then creates new dictionaries containing only the 'id' and 'name' fields for the matching users. This is a concise and efficient way to process structured data, common when handling API responses or database query results, allowing for complex transformations in a single line.

Need help integrating this into your project?

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

Hire DigitalCodeLabs