5 Best Ways to Reverse a Python Dictionary

5/5 - (1 vote)

Problem Formulation and Solution Overview

In this article, you’ll learn how to reverse a Dictionary in Python.

To make it more fun, we have the following running scenario:

We have a Python Dictionary containing three (3) users who are signed up at the Finxter Academy. The current key:value pairs consist of username:id. The owner would like the key:value pairs reversed to be id:username.

💬 Question: How would we write Python code to reverse the key:value pairs in a Dictionary?

We can accomplish this task by one of the following options:


Method 1: Use Dictionary Comprehension

This method uses a Dictionary Comprehension and a For loop to access the key:value pairs by calling users.items(). Each pair is evaluated, and the key:value pairs are reversed.

users      = {'wildone92': 30022145, 'AliceM': 30022359, 'kirbster': 30022467}
reverse_me = {v: k for k, v in users.items()}
print(reverse_me)

This code declares a Dictionary containing three (3) key:value pairs and saves it to users.

Next, Dictionary Comprehension retrieves the key:value pairs by calling users.items(). Then, a For loop iterates through each pair, reversing each username:id key:value pair to id:usernames. The result saves to reverse_me.

Finally, the reversed Dictionary is output to the terminal.

💡 Note: The keys and values must be unique for this code to work as expected.

Output

{30022145: 'wildone92', 30022359: 'AliceM', 30022467: 'kirbster'}

Method 2: Use dict()

This method uses dict() to create a new Dictionary and a For loop to access the key:value pairs by calling dict.items(). Each pair is evaluated, and the key:value pairs are reversed.

users      = {'wildone92': 30022145, 'AliceM': 30022359, 'kirbster': 30022467}
reverse_me = dict((v, k) for k, v in users.items())
print(reverse_me)

This code declares a Dictionary with three (3) key:value pairs and saves it to users.

Next, a new Dictionary (dict()) is created and retrieves the key:value pairs in users as value:key ((v, k)) thus reversing the contents. Then, the reversed content (for k, v in users.items())) saves to reverse_me.

Finally, the reversed Dictionary is output to the terminal.

💡 Note: The keys and values must be unique for this code to work as expected.

Output

{30022145: 'wildone92', 30022359: 'AliceM', 30022467: 'kirbster'}

Method 3: Use dict() and map()

This method is used dict() to create a new Dictionary and map() convert an iterable into a new one. By passing reversed as an argument to map() the key:value pairs are automatically reversed.

users      = {'wildone92': 30022145, 'AliceM': 30022359, 'kirbster': 30022467}
reverse_me = dict(map(reversed, users.items()))
print(reverse_me)

This code declares a Dictionary with three (3) key: value pairs and saves it to users.

Next, a new Dictionary (dict()) is created and retrieves the key:value pairs by calling users.items(). Then, the argument reversed is passed to map() which reverses the key:value pairs. The result saves to reverse_me.

Finally, the reversed Dictionary is output to the terminal.

💡 Note: The keys and values must be unique for this code to work as expected.

Output

{30022145: 'wildone92', 30022359: 'AliceM', 30022467: 'kirbster'}

Method 4: Use dict() and zip()

This method uses dict() to create a new Dictionary and zip() to create an iterable Tuple to pass users.values(), and users.keys() in that order to reverse the contents.

users      = {'wildone92': 30022145, 'AliceM': 30022359, 'kirbster': 30022467}
reverse_me = dict(zip(users.values(), users.keys()))
print(reverse_me)

This code declares a Dictionary with three (3) key: value pairs and saves it to users.

Next, a new Dictionary (dict()) is created and zip() is called. By passing users.values() and users.keys() as arguments to zip() in that order, the key:value pairs are reversed as value:key pairs. The result saves to reverse_me.

Finally, the reversed Dictionary is output to the terminal.

💡 Note: The keys and values must be unique for this code to work as expected.

Output

{30022145: 'wildone92', 30022359: 'AliceM', 30022467: 'kirbster'}

Method 5: Use a Lambda

This method uses a dict(), map(), and a Lambda to loop through the key:value pairs of users and reverse the contents.

users      = {'wildone92': 30022145, 'AliceM': 30022359, 'kirbster': 30022467}
reverse_me = dict(map(lambda key: (users[key], key), users.keys()))
print(reverse_me)

This code declares a Dictionary with three (3) key: value pairs and saves it to users.

Next, a new Dictionary (dict()) is created and map() is used to create a new object. Lambda is used to access each key:value pair and reverse the contents. The result saves to reverse_me.

Finally, the reversed Dictionary is output to the terminal.

💡 Note: The keys and values must be unique for this code to work as expected.

Output

{30022145: 'wildone92', 30022359: 'AliceM', 30022467: 'kirbster'}

Bonus: Reverse for Duplicate

This example contains one (1) duplicate user, AliceM. Running this code will remove the duplicate key:value pair from users and reverse the order of the remaining entries.

users = {'wildone92': 30022145, 'AliceM': 30022359, 'kirbster': 30022467, 'AliceM': 30022359}
reverse_me = {}

for k, v in users.items():
    reverse_me[v] = k
print(reverse_me)

This code declares a Dictionary with four (4) key: value pairs, containing one (1) duplicate key:value pair, and saves it to users.

A For loop is instantiated to loop through all key:value pairs found in users.items(). If the key:value pair is unique, the contents are reversed and appended to reverse_me.

Finally, the reversed Dictionary is output to the terminal.

Output

{30022145: 'wildone92', 30022359: 'AliceM', 30022467: 'kirbster'}

Summary

These five (5) methods of Reversing a Dictionary should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!