PYTHON
Build Fast Lookup Dictionaries from Lists
Learn to efficiently transform lists of objects or key-value pairs into dictionaries for rapid data retrieval, a crucial optimization in web applications.
# Simulate database records or API responses
users_list = [
{'id': 101, 'name': 'Alice', 'email': '[email protected]'},
{'id': 102, 'name': 'Bob', 'email': '[email protected]'},
{'id': 103, 'name': 'Charlie', 'email': '[email protected]'},
]
products_list = [
{'product_id': 'P001', 'name': 'Laptop', 'price': 1200},
{'product_id': 'P002', 'name': 'Mouse', 'price': 25},
{'product_id': 'P003', 'name': 'Keyboard', 'price': 75},
]
# Example 1: Create a user lookup dictionary by ID
user_by_id = {user['id']: user for user in users_list}
print(f"User 102 details: {user_by_id.get(102)}")
# Output: {'id': 102, 'name': 'Bob', 'email': '[email protected]'}
print(f"User 999 details (non-existent): {user_by_id.get(999, 'Not Found')}")
# Example 2: Create a product lookup dictionary by product_id, storing only specific attributes
product_name_by_id = {p['product_id']: p['name'] for p in products_list}
print(f"Name of product P002: {product_name_by_id.get('P002')}")
# Output: Mouse
# Example 3: Building a dictionary from two separate lists (e.g., headers and values)
headers = ['Authorization', 'Content-Type', 'Accept']
values = ['Bearer token123', 'application/json', '*/*']
request_headers = dict(zip(headers, values))
print(f"Request Headers: {request_headers}")
# Output: {'Authorization': 'Bearer token101', 'Content-Type': 'application/json', 'Accept': '*/*'}
How it works: When working with lists of objects (like database results or API payloads), it's common to need fast access to individual items based on a unique identifier. This snippet demonstrates how to use dictionary comprehensions and the `dict(zip())` constructor to efficiently transform such lists into dictionaries where a specific key (e.g., `id`, `product_id`) maps directly to the corresponding object or a chosen attribute. This avoids slow linear searches, significantly speeding up data retrieval in web applications.