PYTHON
Invert Dictionary Keys and Values
Discover how to invert a Python dictionary, swapping its keys and values to create a reverse lookup map, useful for transforming data mappings or creating reverse indices.
def invert_dictionary(input_dict):
"""Inverts a dictionary, swapping keys and values.
Note: If multiple original keys map to the same value,
only the last key encountered for that value will be preserved.
Values must be hashable to become new keys.
"""
# Using a dictionary comprehension for conciseness
return {value: key for key, value in input_dict.items()}
# Example Usage:
country_codes = {
"USA": "+1",
"Canada": "+1", # Duplicate value: Canada will overwrite USA if inverted
"UK": "+44",
"Germany": "+49"
}
# Invert the dictionary
country_names_by_code = invert_dictionary(country_codes)
# print(country_names_by_code)
# Expected output: {'+1': 'Canada', '+44': 'UK', '+49': 'Germany'}
# Notice 'USA' is lost because '+1' key was overwritten by 'Canada'.
status_mapping = {"active": 1, "inactive": 0, "pending": 2}
status_names = invert_dictionary(status_mapping)
# print(status_names)
# Expected output: {1: 'active', 0: 'inactive', 2: 'pending'}
How it works: This snippet demonstrates how to invert a Python dictionary, effectively swapping its keys and values. This is achieved concisely using a dictionary comprehension. It's important to note a key characteristic: if multiple original keys share the same value, only the key corresponding to the *last* occurrence of that value during iteration will be preserved in the inverted dictionary. Additionally, the original values must be hashable (e.g., strings, numbers, tuples) to be used as new keys.