PYTHON
Inverting a Dictionary for Reverse Lookups
Transform a Python dictionary by swapping its keys and values, enabling efficient reverse lookups for data mapping and configuration management.
def invert_dictionary(input_dict):
inverted_dict = {}
for key, value in input_dict.items():
if value in inverted_dict:
# Handle cases where multiple keys map to the same value
# Store values in a list (many-to-one becomes one-to-many)
if isinstance(inverted_dict[value], list):
inverted_dict[value].append(key)
else:
inverted_dict[value] = [inverted_dict[value], key]
else:
inverted_dict[value] = key
return inverted_dict
# Example 1: Simple inversion (unique values)
country_codes = {"USA": "US", "Canada": "CA", "Mexico": "MX"}
code_countries = {code: country for country, code in country_codes.items()}
# Result: {'US': 'USA', 'CA': 'Canada', 'MX': 'Mexico'}
# Example 2: Inversion with potential duplicate values (many-to-one)
role_permissions = {"admin": "full", "editor": "full", "viewer": "read"}
permissions_roles = invert_dictionary(role_permissions)
# Result: {'full': ['admin', 'editor'], 'read': 'viewer'}
How it works: This snippet demonstrates how to invert a dictionary, swapping its keys and values. This is useful for creating reverse lookup tables, such as finding a country name from its code, or roles associated with a specific permission level. The `invert_dictionary` function is provided to handle cases where multiple original keys might map to the same value. In such scenarios, the function stores all original keys that share a value in a list for the new inverted key, preventing data loss that would occur with a simple dictionary comprehension if values are not unique.