PYTHON
Transform and Filter Dictionaries with Comprehensions
Leverage Python's dictionary comprehensions to concisely create new dictionaries, filter existing ones, or transform keys and values, a powerful technique for data manipulation in web apps.
# Original dictionary
products = {
"item1": {"name": "Laptop", "price": 1200, "category": "Electronics"},
"item2": {"name": "Mouse", "price": 25, "category": "Electronics"},
"item3": {"name": "Keyboard", "price": 75, "category": "Electronics"},
"item4": {"name": "Desk Chair", "price": 300, "category": "Furniture"},
"item5": {"name": "Monitor", "price": 350, "category": "Electronics"}
}
# 1. Create a new dictionary with prices above a threshold
expensive_products = {
p_id: details for p_id, details in products.items() if details['price'] > 100
}
print("Expensive products (price > 100):", expensive_products)
# 2. Transform values: Create a dictionary of product names and their discounted prices
discount_percentage = 0.10
discounted_prices = {
details['name']: round(details['price'] * (1 - discount_percentage), 2)
for details in products.values()
}
print("Discounted prices:", discounted_prices)
# 3. Swap keys and values (assuming unique values for keys)
# Original: {id: name} -> New: {name: id}
user_status = {"user_1": "active", "user_2": "inactive", "user_3": "active"}
status_to_users = {
status: [u for u, s in user_status.items() if s == status]
for status in set(user_status.values())
}
print("Users by status:", status_to_users)
How it works: This snippet showcases the versatility of dictionary comprehensions for advanced data manipulation. It demonstrates how to filter dictionary items based on conditions, transform values (e.g., calculate discounted prices), and even invert key-value pairs (grouping users by their status). This technique provides a concise and readable way to create new dictionaries from existing ones.