Reverse a Dictionary in Python

This article demonstrates different methods to invert a dictionary in Python.
Please enable JavaScript
Reversing a dictionary is different from reversing a list, it means to invert or switch the key and value elements of the dictionary, essentially swapping them for whatever purpose the developer might use it for.
Use items() to Reverse a Dictionary in Python
Python dictionaries have a built-in function called items() which returns an iterable object that will display the dictionaries’ key-value pairs in the form of a tuple.
For example, declare a dictionary of random categories and print it out using items() .
Printing a dictionary using items() will output an iterable list of tuple values that we can manipulate using the for loop for dictionaries.
Reverse the key-value pairs by looping the result of items() and switching the key and the value.
The k and v in the for loop stands for key and value respectively. v: k are the placeholders for the key and value in each iteration, although we set the previous value v as the new key and the previous key k as the new value.
The key and the value elements are now reversed in the output.
Same Valued Keys in a Reversed Dictionary
Another example scenario when inverting a dictionary is if there are multiple keys or values with the same value. This is a more likely scenario to invert a dictionary.
For example, a dictionary of people’s favorite animals.
If the dictionary is inverted using the above code, the output would not be as you’d expect.
Here, 2 elements from the original dictionary are missing because every time a key or a value repeats in the loop, the existing record will be overwritten.
The dictionary contains 3 people with the value pair Dog but only James was copied because this was the last record with the value of Dog and has overwritten the 2 other dictionary items.
To solve this problem, we would have to store the values in a list so they would be assigned to a single key.
The complete example code:
Use collections.defaultdict() to Reverse a Dictionary in Python
The module collections has a function defaultdict() which can manipulate the values in a dictionary in Python.
defaultdict() mainly is used for creating default values of non-existent keys. If you access a non-existent key, it can declare a default value for it, even if it doesn’t exist.
This function is useful for our case because we want to instantiate a new dictionary with values that are of a list data type.
Using the same example favAnimal , invert the dictionary and convert the values to a list.
First, initialize the new dictionary using defaultdict()
Next, use the list comprehension for inversion and store the inverted values into the new dictionary.
Lastly, since defaultdict() creates a sort of a subclass of a dictionary, re-convert it to the base dictionary type by wrapping it in dict() .
John, Jenny, and James now are on the same list with the key Dog instead of the other elements being overwritten by the last element that had Dog as their value.
The complete example code:
In summary, use items() to loop over the dictionary and invert the keys and values. If by any chance your data set is likely to have duplicates, then make sure to convert the values into a list by using defaultdict() and manipulate it in a way that the values of the dictionary will append into the list instead of replacing the existing values.
Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.
How to Reverse a Dictionary in Python?

Python is a useful programming language for scripting, data science, and web development. In Python, a dictionary is an unordered collection of data values, similar to a map, that retains the key: value pair, unlike other data types that only hold a single value as an element. A dictionary stores its elements in key-value mapping style and uses hashing internally; as a result, we can rapidly retrieve a value from the dictionary by its key.
When working with dictionaries in python, we may encounter situations where we need to reverse the order of the dictionaries. It is common with applications in a number of domains, including web development and day-to-day programming. Let’s look at some possible solutions to this situation and learn how python reverse dictionary.
Methods to Reverse Dictionary in Python
Reversing a dictionary is not the same as reversing a list; it entails inverting or switching the dictionary’s key and value parts, basically swapping them for whatever purpose the developer has in mind. Below are 3 methods by which you can reverse a dictionary in python:
1) Using OrderedDict() and items() method
This method is for Python versions prior to 2.7. Because older versions don’t retain the ordered nature of dictionaries and so, you’ll need to convert to OrderedDict to complete this work. Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.
Note that before beginning to reverse the dictionary using this method, you have to import the OrderedDict library from the collections module of python using the «from..import» keyword as shown in the below example.
For example:
Ouput:
2) Using reversed() and items() method
This problem can be solved using a mixture of the preceding functions. This is for newer python versions 3.6+ that have a dictionary in the incoming element order. Therefore, we do not have to make use of the OrderedDict() method for preserving the order of the dictionary.
For example:
Output:
3) Using loop and reversed() method
In this method, you initialize a new empty dictionary for storing the reversed items of the original dictionary. Later, using the for loop you traverse through the original list and store every key-value pair in the new empty dictionary after reversing it using reversed() method. Check out the example below for a better understanding.
For example:
Output:
Summary
In summary, dictionaries are python’s version of an associative array and widely used data structure in the technical domain. As dictionaries are mainly used during python programming, there are times when you wish to reverse it externally. Here we have presented various methods by which you can reverse the dictionaries in python effortlessly and make your programming efficient.
Инвертировать отображение словаря Python
В этом посте мы обсудим, как инвертировать сопоставление словаря в Python. Предположим, что все значения в словаре уникальны.
1. Использование словарного понимания
Простое решение для инвертирования каждой пары ключ/значение словаря — использование понимания словаря, как показано ниже:
Кроме того, вы можете использовать конструктор словаря.
2. Использование словарных итераторов
Самое быстрое решение — использовать итераторы словаря для перебора ключей словаря и создания нового словаря с обратным отображением.
3. Использование map() функция
встроенный map() function предоставляет удобный способ применить функцию к каждому элементу iterable. Вы можете использовать это для создания обратного словаря, как показано ниже:
4. Преобразование на месте
Если вам нужно изменить словарь на месте вместо создания нового словаря вы можете создать копию словаря и обновить ее с помощью пар значение-ключ. Это показано ниже:
Как обрабатывать дубликаты?
Если значения словаря не уникальны, вы можете использовать простой цикл for для обработки повторяющихся значений в словаре. Это показано ниже:
Вот и все об инвертировании отображения словаря Python.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 20
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
Как перевернуть словарь python
Sometimes, while working with dictionary, we can have a problem in which we need to reverse the order of dictionary. This is quite a common problem and can have application in many domains including day-day programming and web development. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using OrderedDict() + reversed() + items() This method is for older versions of Python. Older versions don’t keep order in dictionaries, hence have to converted to OrderedDict to execute this task.
Python3
Method #2 : Using reversed() + items() The combination of above functions can be used to solve this problem. This is for newer versions of Python, which have dictionary in incoming order of elements.
Python3
Method #3 : Using deque
Approach
we use the deque data structure from the collections module to reverse the order of the dictionary keys. We then create a new dictionary object using a dictionary comprehension and the reversed keys and original values. Finally, we use the dict() constructor to convert the new dictionary to an OrderedDict object.
Algorithm
1. Create a deque object from the dictionary keys using the deque() function.
2. Use the reverse() method of the deque object to reverse the order of the keys.
3. Create a new dictionary object using a dictionary comprehension and the reversed keys and original values.
4. Use the dict() constructor to convert the new dictionary to an OrderedDict object.
5. Return the new OrderedDict.