How to Swap Keys and Values in a Python Dictionary
This guide explains how to swap the keys and values of a dictionary in Python, creating a new dictionary where the original values become keys, and the original keys become values. We'll cover dictionary comprehensions, the dict()
constructor with generator expressions, for
loops, and the zip()
function, highlighting the best approaches and addressing the critical issue of duplicate values.
Swapping Keys and Values with a Dictionary Comprehension (Recommended)
A dictionary comprehension provides the most concise and Pythonic way to swap keys and values, assuming the values are unique:
my_dict = {
'tom': 'first',
'nolan': 'last',
'python': 'topic',
}
new_dict = {value: key for key, value in my_dict.items()}
print(new_dict)
# Output: {'first': 'tom', 'last': 'nolan', 'topic': 'python'}
my_dict.items()
: Returns a view object containing (key, value) pairs as tuples.{value: key ...}
: This is the dictionary comprehension. It iterates through the (key, value) pairs and creates a new dictionary where the values become keys and the keys become values.
Handling Duplicate Values
The simple dictionary comprehension above will overwrite entries if there are duplicate values in the original dictionary. Since keys must be unique in a dictionary, only the last key associated with a duplicate value will be kept.
my_dict = {
'tom': 'first',
'nolan': 'last',
'python': 'topic',
'django': 'topic', # Duplicate value: 'topic'
'flask': 'topic', # Duplicate value: 'topic'
}
new_dict = {value: key for key, value in my_dict.items()}
print(new_dict) # Output: {'first': 'tom', 'last': 'nolan', 'topic': 'flask'}
To handle duplicate values and keep all original keys, you need to store the keys as lists in the new dictionary:
my_dict = {
'tom': 'first',
'nolan': 'last',
'python': 'topic',
'django': 'topic',
'flask': 'topic',
}
new_dict = {}
for key, value in my_dict.items():
if value in new_dict:
new_dict[value].append(key) # Append to existing list
else:
new_dict[value] = [key] # Create a new list
print(new_dict)
# Output: {'first': ['tom'], 'last': ['nolan'], 'topic': ['python', 'django', 'flask']}
- This code iterates through the original dictionary.
- If a value already exists as a key in
new_dict
, the corresponding key frommy_dict
is appended to the list associated with that value. - If a value is not already a key in
new_dict
, a new key-value pair is created, with the value as the key and a list containing the original key as the value. - This method is also not as efficient or readable as other methods.
Swapping Keys and Values with dict()
and a Generator Expression
You can combine the dict()
constructor with a generator expression for another concise way to swap (assuming unique values):
my_dict = {
'tom': 'first',
'nolan': 'last',
'python': 'topic',
}
new_dict = dict((value, key) for key, value in my_dict.items())
print(new_dict) # Output: {'first': 'tom', 'last': 'nolan', 'topic': 'python'}
(value, key) for key, value in my_dict.items()
: This is a generator expression that yields (value, key) tuples.dict(...)
: Thedict()
constructor can accept an iterable of key-value pairs (like the tuples produced by the generator).
This is functionally equivalent to the dictionary comprehension and is a matter of preference.
Swapping Keys and Values with a for
Loop
A for
loop provides the most explicit way to swap, and it's easier to adapt for handling duplicate values (as shown above):
my_dict = {
'tom': 'first',
'nolan': 'last',
'python': 'topic',
}
new_dict = {}
for key, value in my_dict.items():
new_dict[value] = key # Simple swap (will overwrite duplicates)
print(new_dict) # Output: {'first': 'tom', 'last': 'nolan', 'topic': 'python'}
This is the code to use if the values in the original dictionary are unique.
Swapping Keys and Values with zip()
The zip()
function can be used to pair up the values and keys, and then dict()
can create the new dictionary:
my_dict = {
'tom': 'first',
'nolan': 'last',
'python': 'topic',
}
new_dict = dict(zip(my_dict.values(), my_dict.keys()))
print(new_dict) # Output: {'first': 'tom', 'last': 'nolan', 'topic': 'python'}
my_dict.values()
: Gets a view of the dictionary's values.my_dict.keys()
: Gets a view of the dictionary's keys.zip(...)
: Pairs up corresponding values and keys.dict(...)
: Creates a dictionary from the zipped pairs. This approach is concise, but potentially less readable than a dictionary comprehension. It also assumes unique values, like other alternatives.