PYTHON
Invert a Dictionary to Swap Keys and Values
Learn to create a new dictionary by swapping the keys and values of an existing one, useful for reverse lookups or data transformations in Python web projects and APIs.
original_dict = {'user_id': 101, 'product_id': 203, 'order_id': 305}
status_codes = {
'OK': 200,
'Created': 201,
'Bad Request': 400,
'Not Found': 404
}
# Simple inversion where values are unique and hashable
inverted_dict_simple = {value: key for key, value in original_dict.items()}
print(f"Original: {original_dict}")
print(f"Inverted (simple): {inverted_dict_simple}")
# Inverting where values might not be unique (create list of keys for each value)
from collections import defaultdict
def invert_dict_multi_value(d):
inverted = defaultdict(list)
for key, value in d.items():
inverted[value].append(key)
return dict(inverted) # Convert back to regular dict if preferred
# Example with non-unique values (imagine multiple users with same role_id)
roles = {
'admin': 1,
'editor': 2,
'viewer': 3,
'super_admin': 1, # duplicate value
'guest': 3 # duplicate value
}
inverted_roles = invert_dict_multi_value(roles)
print(f"
Original roles: {roles}")
print(f"Inverted roles (multi-value): {inverted_roles}")
# Example of inverting status_codes (values are unique)
inverted_status_codes = {value: key for key, value in status_codes.items()}
print(f"
Original status codes: {status_codes}")
print(f"Inverted status codes: {inverted_status_codes}")
How it works: This snippet demonstrates how to invert a Python dictionary, effectively swapping its keys and values. The primary method uses a dictionary comprehension for a concise solution, suitable when all values in the original dictionary are unique and hashable. For cases where values might not be unique, the `invert_dict_multi_value` function utilizes `collections.defaultdict` to create a list of keys for each value, preventing data loss. This technique is invaluable for creating reverse lookup tables, such as mapping status codes back to names or database IDs to corresponding object names in web development scenarios.