PYTHON
Transform Lists of Dictionaries with Python List Comprehensions
Efficiently transform, filter, and restructure lists of dictionaries using Python's concise list comprehensions, ideal for processing API responses or database results.
users_data = [
{"id": 1, "name": "Alice", "email": "[email protected]", "is_active": True},
{"id": 2, "name": "Bob", "email": "[email protected]", "is_active": False},
{"id": 3, "name": "Charlie", "email": "[email protected]", "is_active": True},
]
# Example 1: Extracting specific fields (name and email) for active users
active_user_contacts = [
{"username": user["name"], "contact_email": user["email"]}
for user in users_data if user["is_active"]
]
print(f"Active user contacts: {active_user_contacts}")
# Example 2: Creating a list of just user IDs
user_ids = [user["id"] for user in users_data]
print(f"User IDs: {user_ids}")
# Example 3: Filtering and modifying items in one go (e.g., uppercase names)
modified_active_users = [
{"id": user["id"], "name": user["name"].upper()}
for user in users_data if user["is_active"]
]
print(f"Modified active users: {modified_active_users}")
# Example 4: Creating a dictionary from the list of dictionaries
user_id_to_name = {user["id"]: user["name"] for user in users_data}
print(f"User ID to name map: {user_id_to_name}")
How it works: List comprehensions provide a concise and readable way to create new lists (or other iterables like sets and dictionaries) from existing ones. This snippet shows how to efficiently transform lists of dictionaries – a common structure in web development for data from APIs or databases. You can filter elements based on conditions, select specific keys, rename them, and even perform in-line modifications, all within a single line of code, leading to more Pythonic and performant data manipulation.