• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Reverse A Dictionary in Python

Reverse A Dictionary in Python

Author: Aditya Raj
Last Updated: March 3, 2022

Dictionaries in python are a great tool to store key-value mappings. In this article, we will discuss how to reverse a dictionary in python. We will do it using different examples so that we can understand the approaches in a better manner.

How to Reverse a Dictionary in Python?

When we reverse a given python dictionary, we change the order of values in the key-value pair. In each key-value pair, the current key becomes the value and the current value becomes the key in the new dictionary. For instance, look at the following dictionary.

myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

After we reverse this dictionary, it would look like this.

reversedDict = {1: 1, 4: 2, 9: 3, 16: 4, 25: 5}

To reverse a dictionary in python, we can use a for loop or dictionary comprehension. Let us discuss both approaches one by one.

Reverse a Dictionary in Python Using a For Loop

To reverse a dictionary using for loop, we will first create an empty dictionary to store the reverted key-value pairs. After that, we will traverse over each key-value pair in the input dictionary. While traversal, we will make each value of the input dictionary a key in the output dictionary and the key associated with the value in the input dictionary will be made the associated value in the output dictionary as follows.

myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = dict()
for key in myDict:
    val = myDict[key]
    reversedDict[val] = key
print("The reversed dictionary is:")
print(reversedDict)

Output:

The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}

Using keys() and values() Method

You can also use the keys() and values() method with the for loop to reverse a dictionary. In this approach, we will first make a list of keys and a list of values of the input dictionary. After that, we will make each element of the list of values a key in the output dictionary. The associated element in the list of keys will be made the corresponding value in the output dictionary as follows.

myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = dict()
key_list = list(myDict.keys())
val_list = list(myDict.values())
n = len(key_list)
for i in range(n):
    key = val_list[i]
    val = key_list[i]
    reversedDict[key] = val
print("The reversed dictionary is:")
print(reversedDict)

Output:

The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}

Using items() Method

You can also use the items() method to reverse a dictionary. In this approach, we will take each item from the input dictionary one by one. After that, we will reverse the key-value pair as follows.

myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = dict()
for item in myDict.items():
    key = item[1]
    val = item[0]
    reversedDict[key] = val
print("The reversed dictionary is:")
print(reversedDict)

Output:

The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}

Using Dictionary Comprehension

Instead of using a for loop, we can reverse a dictionary in a single python statement using dictionary comprehension. Here, we will create the output dictionary by reversing the key and value in each key-value pair of the dictionary as follows.

myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = {val: key for (key, val) in myDict.items()}
print("The reversed dictionary is:")
print(reversedDict)

Output:

The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}

Conclusion

In this article, we have discussed four ways to reverse a dictionary in python. To learn more about dictionaries in python, you can read this article on how to convert a dictionary to list of tuples. You might also like this article on list comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us