Swap the keys and values in a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# Table of Contents

  1. Swap the keys and values in a Dictionary in Python
  2. Swap the keys and values in a Dictionary using dict()
  3. Swap the keys and values in a Dictionary using a for loop
  4. Swap the keys and values in a Dictionary using zip()

# Swap the keys and values in a Dictionary in Python

To swap the keys and values in a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a dict comprehension to iterate over the view.
  3. Swap each key and value and return the result.
main.py
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)

swap keys and values in dictionary

The code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
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.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we swap the key and the value and return the result.

main.py
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)

# Swap the keys and values in a Dictionary and handle Duplicate Values

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.

main.py
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)

swap keys and values in dictionary and handle duplicate values

The code for this article is available on GitHub

The original dictionary has multiple values equal to the string topic.

  1. We iterate over the dictionary's items.
  2. On each iteration, we check if the current value is contained in the keys of the new dictionary.
  3. If the condition is met, we append the current key to the list of values in the new dictionary.
  4. Otherwise, we initialize a new key-value pair.

You can also use the dict() class.

# Swap the keys and values in a Dictionary using dict()

This is a three-step process:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a generator expression to iterate over the view object.
  3. Swap each key and value in the call to the dict() class.
main.py
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)
The code for this article is available on GitHub

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.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

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.

# Swap the keys and values in a Dictionary using a for loop

This is a three-step process:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a for loop to iterate over the view object.
  3. Swap each key and value and add them to a new dictionary.
main.py
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)
The code for this article is available on GitHub

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.

# Swap the keys and values in a Dictionary using zip()

This is a three-step process:

  1. Use the dict.keys() and dict.values() methods to get a view of the dictionary's keys and values.
  2. Use the zip() function to produce a tuple with each value and key.
  3. Pass the tuples to the dict() class.
main.py
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 code for this article is available on GitHub

The dict.values() method returns a new view of the dictionary's values.

main.py
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.

main.py
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.

main.py
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 code for this article is available on GitHub

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.

Want to learn more about working with dictionaries in Python? Check out these resources: Check if all values in a Dictionary are equal in Python,How to Replace values in a Dictionary in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev