swap keys and values in a python dictionary

Easily Swap Keys and Values in a Python Dictionary with this method

In this tutorial, we will look at how to swap the keys and values of a Python dictionary with the help of some examples.

If you prefer a video tutorial over text, check out the following video detailing the steps in this tutorial –

How to swap keys and values?

Use dictionary comprehension to reverse the keys and values of a dictionary by iterating through the original keys and values using the dictionary items() function. The following is the syntax –

# swap keys and values of a dictionary
new_dictionary = {v:k for (k, v) in dictionary.items()}

This will return a new dictionary with the keys and values swapped from the original dictionary.

Two crucial caveats when swapping the keys and values –

  1. Make sure the values in the dictionary are unique. This is because the values will become the keys after the swap, and a dictionary can only have unique keys. If duplicate values are present, only one of them will be retained as a key after the swap.
  2. Make sure that the values are hashable types. This is because the values will become the keys after the swap, and a dictionary can only have hashable types as its keys.

Examples

Let’s now look at some examples of using the above syntax –

# create a dictionary
d = {
    "Emp1": "Jim",
    "Emp2": "Dwight",
    "Emp3": "Pam"
}

# swap the keys and values
new_d = {v:k for (k,v) in d.items()}
# display the new dictionary
print(new_d)

Output:

{'Jim': 'Emp1', 'Dwight': 'Emp2', 'Pam': 'Emp3'}

Here, we created a dictionary storing the mapping of employee id to employee name in an office. You can see that after reversing the keys and values we get a dictionary with the employee name as the key and the employee id as the value.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Caveats of swapping keys and values in a Python dictionary

There are a couple of caveats that you should be aware of if you’re swapping the keys and values of a dictionary. Let’s look at them in detail with the help of examples.

Make sure the values in the dictionary are unique

A Python dictionary can only have unique values at its keys. And since after the swap, the values will become the keys, if there are duplicate values in the original dictionary, only one of them will be retained as a key after the swap.

Let’s look at an example – What if in the above dictionary, a new employee joins with the name “Dwight”?

# create a dictionary
d = {
    "Emp1": "Jim",
    "Emp2": "Dwight",
    "Emp3": "Pam",
    "Emp4": "Dwight"
}

# swap the keys and values
new_d = {v:k for (k,v) in d.items()}
# display the new dictionary
print(new_d)

Output:

{'Jim': 'Emp1', 'Dwight': 'Emp4', 'Pam': 'Emp3'}

You can see that only one “Dwight” (with employee id “Emp4”) is retained as a key in the resulting dictionary and we lose the data for the “Dwight” (with employee id “Emp2”).

Make sure that the values are hashable types

A Python dictionary can only have hashable type values at its keys. For example, you cannot use a list as a key to a Python dictionary since it’s not a hashable type (you can, however, use a tuple as it is a hashable type).

So, if the original dictionary has non-hashable type values, if you try to swap them as keys to a new dictionary, you’ll get a TypeError. Let’s look at an example.

# create a dictionary
d = {
    2019 : "Jim",
    2020 : ["Dwight", "Angela"],
    2021 : "Pam",
}

# swap the keys and values
new_d = {v:k for (k,v) in d.items()}
# display the new dictionary
print(new_d)

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[4], line 9
      2 d = {
      3     2019 : "Jim",
      4     2020 : ["Dwight", "Angela"],
      5     2021 : "Pam",
      6 }
      8 # swap the keys and values
----> 9 new_d = {v:k for (k,v) in d.items()}
     10 # display the new dictionary
     11 print(new_d)

Cell In[4], line 9, in <dictcomp>(.0)
      2 d = {
      3     2019 : "Jim",
      4     2020 : ["Dwight", "Angela"],
      5     2021 : "Pam",
      6 }
      8 # swap the keys and values
----> 9 new_d = {v:k for (k,v) in d.items()}
     10 # display the new dictionary
     11 print(new_d)

TypeError: unhashable type: 'list'

Here, we created a dictionary with the year as the key and the winner of the “Employee of the Year” award as the respective value. Note that in the year 2020, the award was won by two people – “Dwight” and “Angela” and hence we used a list to map that to 2020.

Now, we tried to swap the keys and values in the above dictionary but we got a TypeError. This is because list is an unhashable type and thus cannot be used as a dictionary key.

FAQs

How to swap the keys and values of a Python dictionary?

Use dictionary comprehension to reverse the keys and values of a dictionary by iterating through the original keys and values of the dictionary using the dictionary items() function.

What happens if there are duplicate values in the dictionary when swapping the keys and values?

If there are duplicate values in the dictionary when swapping the keys and values, one of the keys will be overwritten and lost.

What happens if there are unhashable type values in the dictionary when swapping the keys and values?

You’ll get a TypeError as unhashable types can not be used a dictionary keys in Python.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top