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 –
- 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.
- 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.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 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
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.
If there are duplicate values in the dictionary when swapping the keys and values, one of the keys will be overwritten and lost.
You’ll get a TypeError
as unhashable types can not be used a dictionary keys in Python.
You might also be interested in –
- Swap Two Words in a String with these Methods in Python
- Sort Python Dictionary Keys and Values
- Rename a Key in a Python Dictionary
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.