← Back to all snippets
PYTHON

Advanced List Comprehensions for Data Transformation

Efficiently transform and filter data in Python using advanced list comprehensions, creating new lists based on complex conditions and expressions in a single line.

data = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 24, 'city': 'London'},
    {'name': 'Charlie', 'age': 30, 'city': 'Paris'},
    {'name': 'David', 'age': 35, 'city': 'New York'}
]

# Get names of people aged 30 from 'New York'
filtered_names = [
    person['name'] for person in data
    if person['age'] == 30 and person['city'] == 'New York'
]

# Create a dictionary mapping city to a list of names for people under 35 (without collections.defaultdict)
city_people_manual = {}
for person in data:
    if person['age'] < 35:
        city_people_manual.setdefault(person['city'], []).append(person['name'])

# List of (name, city) tuples for people over 25
people_over_25 = [(p['name'], p['city']) for p in data if p['age'] > 25]

print(f"Filtered names (age 30, New York): {filtered_names}")
print(f"People grouped by city (under 35): {city_people_manual}")
print(f"People over 25 (name, city): {people_over_25}")
How it works: This snippet demonstrates list comprehensions for concise data manipulation. The first example filters a list of dictionaries to extract specific names based on age and city criteria. The second shows how to create a dictionary mapping cities to lists of names using a standard loop with `setdefault`, effectively grouping data. The third uses a comprehension to create a list of tuples for people meeting an age criterion, highlighting the power of one-liners for data transformation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs