How to reverse a dictionary in Python
Discover multiple ways to reverse a dictionary in Python. Get tips, see real-world applications, and learn how to debug common errors.

To reverse a Python dict, you swap its keys and values. Since dictionaries don't have a built-in reverse method, you can use several simple techniques to accomplish this task.
In this article, we'll show you several reversal techniques. We'll also cover practical tips, real-world applications, and debugging advice to help you handle potential data conflicts during the swap.
Using dictionary comprehension to reverse a dictionary
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
reversed_dict = {value: key for key, value in original_dict.items()}
print(reversed_dict)--OUTPUT--{1: 'apple', 2: 'banana', 3: 'cherry'}
Dictionary comprehension offers a clean, one-line solution for this task. It works by iterating over the original dictionary's items and creating a new dictionary with the keys and values swapped. The .items() method is key here, as it lets you access each key-value pair during the loop.
The expression {value: key for key, value in original_dict.items()} then rebuilds the dictionary, assigning the original value as the new key and the original key as the new value. This approach is often preferred because it's both efficient and highly readable.
Common dictionary reversal techniques
Beyond comprehension, you can also reverse dictionaries with a for loop or the dict() constructor, though both methods require you to address potential duplicate values.
Using a for loop to reverse a dictionary
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
reversed_dict = {}
for key, value in original_dict.items():
reversed_dict[value] = key
print(reversed_dict)--OUTPUT--{1: 'apple', 2: 'banana', 3: 'cherry'}
Using a for loop is a more explicit, step-by-step approach. The process involves a few key actions:
- First, you initialize an empty dictionary to hold the reversed pairs.
- Then, the loop iterates over each
keyandvaluefrom the original dictionary. - Inside the loop, you simply assign the
valueas the new key and thekeyas the new value.
This method is slightly more verbose than a comprehension but can be easier to follow if you're debugging or new to Python's shorthand.
Using the dict() constructor for reversal
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
reversed_dict = dict((value, key) for key, value in original_dict.items())
print(reversed_dict)--OUTPUT--{1: 'apple', 2: 'banana', 3: 'cherry'}
You can also use the dict() constructor with a generator expression. This approach is functionally similar to a dictionary comprehension but structures the logic a bit differently.
- The generator expression,
(value, key) for key, value in original_dict.items(), iterates through the original dictionary and yields swapped(value, key)tuples. - The
dict()constructor then takes this sequence of tuples and assembles them into a new dictionary.
Handling duplicate values in dictionaries
original_dict = {'apple': 1, 'banana': 2, 'cherry': 1}
reversed_dict = {}
for key, value in original_dict.items():
if value in reversed_dict:
if isinstance(reversed_dict[value], list):
reversed_dict[value].append(key)
else:
reversed_dict[value] = [reversed_dict[value], key]
else:
reversed_dict[value] = key
print(reversed_dict)--OUTPUT--{1: ['apple', 'cherry'], 2: 'banana'}
When you reverse a dictionary, duplicate values in the original can cause data loss since keys in the new dictionary must be unique. This code prevents that by checking for duplicates during the reversal.
- The loop iterates through each item, and the
if value in reversed_dictcondition checks if a value has already been added as a key. - If a duplicate is found, the code groups the corresponding original keys into a list. It uses
isinstance()to see if a list already exists for that value, appending to it or creating a new one as needed.
Advanced dictionary reversal methods
To streamline duplicate handling or tackle more complex structures, you can use advanced methods involving Python's defaultdict, the zip() function, and recursive logic.
Using defaultdict for automatic grouping
from collections import defaultdict
original_dict = {'apple': 1, 'banana': 2, 'cherry': 1, 'date': 3}
reversed_dict = defaultdict(list)
for key, value in original_dict.items():
reversed_dict[value].append(key)
print(dict(reversed_dict))--OUTPUT--{1: ['apple', 'cherry'], 2: ['banana'], 3: ['date']}
The defaultdict from Python's collections module offers a more elegant way to handle duplicates. By initializing it with defaultdict(list), you're telling it to automatically create an empty list whenever you access a key that doesn't exist yet.
- As the loop runs, it takes each original
keyand appends it to the list associated with its correspondingvalue. - This completely removes the need for conditional checks to see if a key already exists, resulting in cleaner and more efficient code.
Using zip() for functional dictionary reversal
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
keys = list(original_dict.keys())
values = list(original_dict.values())
reversed_dict = dict(zip(values, keys))
print(reversed_dict)--OUTPUT--{1: 'apple', 2: 'banana', 3: 'cherry'}
The zip() function offers a functional approach by pairing elements from two separate iterables. This method is straightforward but less direct than a comprehension, as it requires you to first unpack the dictionary's keys and values into their own lists.
- First, you extract all keys and values into two separate lists using
original_dict.keys()andoriginal_dict.values(). - The
zip()function then iterates through both lists simultaneously, creating tuples where each original value is paired with its corresponding key. - Finally, the
dict()constructor takes this sequence of tuples and assembles the new, reversed dictionary.
Reversing a nested dictionary structure
nested_dict = {'fruits': {'apple': 1, 'banana': 2}, 'vegetables': {'carrot': 3, 'potato': 4}}
reversed_nested = {v: (outer_k, inner_k) for outer_k, inner_dict in nested_dict.items()
for inner_k, v in inner_dict.items()}
print(reversed_nested)--OUTPUT--{1: ('fruits', 'apple'), 2: ('fruits', 'banana'), 3: ('vegetables', 'carrot'), 4: ('vegetables', 'potato')}
Reversing a nested dictionary requires a way to track the original key hierarchy. You can do this with a nested dictionary comprehension, which iterates through both the outer and inner dictionaries to access every value.
- The innermost value becomes the new key in the reversed dictionary.
- The new value is a tuple, like
('fruits', 'apple'), that stores the original path of keys. This preserves the context of where each value came from in the original nested structure.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques to building complete applications with tools like Agent 4.
Instead of manually piecing together methods, you can describe the app you want to build and Agent 4 will take it from idea to a working product:
- An inverted index for a product catalog that groups items by category, letting you instantly find all products that are 'fruits' or 'vegetables'.
- A user lookup tool that reverses a dictionary of user IDs and usernames, allowing you to find a user's ID by searching for their name.
- A configuration management utility that finds the exact path of a setting within a nested structure just by searching for its value.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
When reversing a dictionary, you might run into issues like non-hashable values, lost keys from duplicates, and unexpected KeyError exceptions.
Handling non-hashable values when reversing dictionaries
A frequent issue is reversing a dictionary with non-hashable values, like lists. Python dictionary keys must be immutable, so attempting to use a mutable type as a key will result in a TypeError. The code below shows what happens when you try.
original_dict = {'item1': [1, 2, 3], 'item2': [4, 5], 'item3': [1, 2, 3]}
# This will cause TypeError because lists can't be dictionary keys
reversed_dict = {value: key for key, value in original_dict.items()}
print(reversed_dict)
The code triggers a TypeError because lists like [1, 2, 3] are mutable and can't be used as dictionary keys. To get around this, you'll need to adjust the values during the swap. The code below shows how.
original_dict = {'item1': [1, 2, 3], 'item2': [4, 5], 'item3': [1, 2, 3]}
# Convert lists to tuples (which are hashable)
reversed_dict = {tuple(value): key for key, value in original_dict.items()}
print(reversed_dict)
The fix is to convert each list into a tuple using tuple(value) inside the comprehension. Since tuples are immutable, they are hashable and can legally serve as dictionary keys, which resolves the TypeError.
This is a common issue to watch for whenever your original dictionary's values are mutable types—like lists, sets, or other dictionaries—that you intend to use as keys in the reversed dictionary.
Detecting lost keys due to duplicate values with dict comprehension
Using a dict comprehension is clean, but it can silently overwrite data if your original dictionary has duplicate values. Since the new keys must be unique, only the last key-value pair for a given value is kept. The following code shows this in action.
original_dict = {'apple': 1, 'banana': 2, 'cherry': 1}
reversed_dict = {value: key for key, value in original_dict.items()}
print(reversed_dict) # Only one key with value 1 will be kept
Because the value 1 appears twice, the comprehension first assigns 'apple' to it, then overwrites it with 'cherry'. This means the 'apple' key is silently dropped. The following code demonstrates how to detect and handle these duplicates.
original_dict = {'apple': 1, 'banana': 2, 'cherry': 1}
from collections import defaultdict
reversed_dict = defaultdict(list)
for key, value in original_dict.items():
reversed_dict[value].append(key)
print(dict(reversed_dict))
To prevent data loss, use defaultdict(list) from the collections module. This approach automatically groups original keys into a list when their values are the same. As the loop iterates, reversed_dict[value].append(key) adds each key to a list associated with its value. This cleanly handles duplicates without manual checks, ensuring no keys are silently dropped. You should watch for this issue whenever your original dictionary's values might not be unique.
Avoiding KeyError when accessing reversed dictionaries
A KeyError is a common issue after reversing a dictionary, happening when you try to access a key that doesn't exist. Since the original values become the new keys, searching for a non-existent value will trigger this error. The code below shows what happens when you try to access the key 4.
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
reversed_dict = {value: key for key, value in original_dict.items()}
# This will raise KeyError if the value doesn't exist
print(reversed_dict[4])
This code triggers a KeyError because it directly accesses reversed_dict[4], assuming the key exists. Since 4 was not a value in the original dictionary, the lookup fails. The following code demonstrates a safer approach.
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
reversed_dict = {value: key for key, value in original_dict.items()}
# Use .get() method with a default value
print(reversed_dict.get(4, "Value not found"))
The fix is to use the .get() method instead of direct key access. This method safely retrieves a value by letting you provide a default, like "Value not found", which is returned if the key doesn't exist. This prevents the program from crashing with a KeyError. You should use this approach whenever you're looking up a key that might not be present, ensuring your code handles missing data gracefully.
Real-world applications
Beyond simple {value: key} swaps, dictionary reversal powers practical features like reverse lookups and two-way URL routing in real-world applications.
Using .items() for country code reverse lookup
For a country code lookup, you can use .items() within a dictionary comprehension to reverse the mapping and find a country's name from its code.
country_codes = {'United States': 'US', 'Canada': 'CA', 'United Kingdom': 'UK'}
code_to_country = {code: country for country, code in country_codes.items()}
user_code = 'UK'
print(f"The country code {user_code} represents {code_to_country[user_code]}")
This example creates a two-way lookup by inverting a dictionary. It starts with a country_codes dictionary that maps full country names to their abbreviations.
- A dictionary comprehension quickly builds a new
code_to_countrydictionary, swapping the original keys and values. - This makes it possible to find a country's name using its code. For instance, you can now use the code
'UK'to retrieve the name'United Kingdom'.
The final print() statement simply displays the result of this reverse lookup.
Building a two-way mapping with {value: key} comprehension for URL routing
In web frameworks, reversing a route map with a comprehension allows you to look up an endpoint name, like profile, from its corresponding URL path, such as /users/profile.
routes = {
'home': '/',
'profile': '/users/profile',
'settings': '/users/settings',
'logout': '/auth/logout'
}
path_to_endpoint = {path: endpoint for endpoint, path in routes.items()}
requested_path = '/users/profile'
print(f"Endpoint for path '{requested_path}': {path_to_endpoint[requested_path]}")
This example builds a two-way lookup system. It starts with a routes dictionary where endpoint names are keys and URL paths are values. A dictionary comprehension then inverts this mapping to create the path_to_endpoint dictionary.
- The expression
{path: endpoint for ...}iterates through the original items, swapping each key and value. - This new dictionary lets you find an endpoint's name using its URL path as the key.
- The code then uses this reversed map to find that the path
'/users/profile'corresponds to the'profile'endpoint.
Get started with Replit
Now, turn these techniques into a real tool. Tell Replit Agent to “build a state code to name converter” or “create a reverse lookup tool for user IDs and usernames.”
Replit Agent writes the code, tests for errors, and deploys your application directly from your browser. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



