Last updated: Apr 10, 2024
Reading timeยท5 min
To swap the keys and values in a dictionary:
dict.items()
method to get a view of the dictionary's items.my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } new_dict = { value: key for key, value in my_dict.items() } # ๐๏ธ {'first': 'bobby', 'last': 'hadz', 'topic': 'python'} print(new_dict)
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } # ๐๏ธ dict_items([('bobby', 'first'), ('hadz', 'last'), ('python', 'topic')]) print(my_dict.items())
We used a dict comprehension to iterate over the view object.
Dict comprehensions are very similar to list comprehensions.
On each iteration, we swap the key and the value and return the result.
my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } new_dict = { value: key for key, value in my_dict.items() } # ๐๏ธ {'first': 'bobby', 'last': 'hadz', 'topic': 'python'} print(new_dict)
The keys in a dictionary are unique so trying to add the same key to a dictionary multiple times simply overrides the value of the key.
If you try to swap the keys and values of a dictionary that contains duplicate values, you'd lose some of the key-value pairs.
One way to get around this is to store the values in the new dictionary using a list.
my_dict = { 'bobby': 'first', 'hadz': '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) else: new_dict[value] = [key] # {'first': ['bobby'], # 'last': ['hadz'], # 'topic': ['python', 'django', 'flask']} print(new_dict)
The original dictionary has multiple values equal to the string topic
.
You can also use the dict()
class.
This is a three-step process:
dict.items()
method to get a view of the dictionary's items.dict()
class.my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } new_dict = dict( (value, key) for key, value in my_dict.items() ) # ๐๏ธ {'first': 'bobby', 'last': 'hadz', 'topic': 'python'} print(new_dict)
We used the dict.items()
method to get a view of the dictionary's items and
used a
generator expression
to iterate over the view object.
On each iteration, we return a tuple containing the value and key.
The dict()
class can be passed an iterable of key-value pairs and returns a
new dictionary.
Alternatively, you can use a simple for loop.
This is a three-step process:
dict.items()
method to get a view of the dictionary's items.for
loop to iterate over the view object.my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } new_dict = {} for key, value in my_dict.items(): new_dict[value] = key # ๐๏ธ {'first': 'bobby', 'last': 'hadz', 'topic': 'python'} print(new_dict)
We declared a new variable that stores an empty dictionary.
We used a for
loop to iterate over the items of the original dictionary.
On each iteration, we swap each key and value and assign the pair to the new dictionary.
Alternatively, you can use the zip()
function.
This is a three-step process:
dict.keys()
and dict.values()
methods to get a view of the
dictionary's keys and values.zip()
function to produce a tuple with each value and key.dict()
class.my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } new_dict = dict( zip(my_dict.values(), my_dict.keys()) ) # ๐๏ธ {'first': 'bobby', 'last': 'hadz', 'topic': 'python'} print(new_dict)
The dict.values() method returns a new view of the dictionary's values.
my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } # ๐๏ธ dict_values(['first', 'last', 'topic']) print(my_dict.values()) # ๐๏ธ dict_keys(['bobby', 'hadz', 'python']) print(my_dict.keys())
The dict.keys() method returns a new view of the dictionary's keys.
The zip() function iterates over several iterables in parallel and produces tuples with an item from each iterable.
The zip
function returns an iterator of tuples.
my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } # ๐๏ธ [('first', 'bobby'), ('last', 'hadz'), ('topic', 'python')] print(list(zip( my_dict.values(), my_dict.keys() )))
The last step is to pass the iterator of tuples to the dict()
class.
my_dict = { 'bobby': 'first', 'hadz': 'last', 'python': 'topic', } new_dict = dict( zip(my_dict.values(), my_dict.keys()) ) # ๐๏ธ {'first': 'bobby', 'last': 'hadz', 'topic': 'python'} print(new_dict)
Which approach you pick is a matter of personal preference. I'd use a dict comprehension as I find them quite direct and easy to read.
You can learn more about the related topics by checking out the following tutorials: