PYTHON
Invert a Dictionary (Swap Keys and Values)
Discover how to invert a Python dictionary, effectively swapping its keys with its values. Learn a concise method using dictionary comprehension for a fundamental data transformation.
original_dict = {
"apple": 1,
"banana": 2,
"orange": 3
}
# Invert the dictionary (keys become values, values become keys)
# This works best when values are unique and hashable.
# If values are not unique, some data will be lost (last key for that value wins).
inverted_dict = {value: key for key, value in original_dict.items()}
print(inverted_dict)
# Example with non-unique values (data loss for 'banana' key)
color_codes = {
"red": "#FF0000",
"crimson": "#FF0000",
"green": "#00FF00"
}
inverted_color_codes = {value: key for key, value in color_codes.items()}
print(inverted_color_codes)
# Expected output:
# {1: 'apple', 2: 'banana', 3: 'orange'}
# {'#FF0000': 'crimson', '#00FF00': 'green'}
How it works: This snippet demonstrates how to invert a dictionary, effectively swapping its keys and values, using a concise dictionary comprehension. This operation is useful when you need to quickly look up the original key based on its associated value. It's important to note that this works best when the original dictionary's values are unique and hashable; if values are duplicated, the last key associated with that value in the iteration will be the one stored in the inverted dictionary, leading to potential data loss.