Reverse dictionary in python

How to Reverse a Dictionary in Python?

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:

Читайте также:  Pseudo classes and pseudo elements in css

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:

from collections import OrderedDict # initializing dictionary test_dict = 'silver' : 4, 'gold' : 2, 'diamond' : 5> print("The original dictionary : " + str(test_dict)) res = OrderedDict(reversed(list(test_dict.items()))) # printing dictionary in reversed order print("The dictionary in reversed order : " + str(res))
The original dictionary : 'silver': 4, 'gold': 2, 'diamond': 5> The dictionary in reversed order : OrderedDict([('diamond', 5), ('gold', 2), ('silver', 4)])

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:

# initializing dictionary test_dict = 'silver' : 4, 'gold' : 2, 'diamond' : 5> # printing original dictionary print("The original dictionary : " + str(test_dict)) res =dict(reversed(list(test_dict.items()))) # printing reversed order dictionary print("The reversed order dictionary : " + str(res))
The original dictionary : 'silver': 4, 'gold': 2, 'diamond': 5> The reversed order dictionary : 'diamond': 5, 'gold': 2, 'silver': 4>

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:

test_dict1 = 'silver': 4, 'gold': 2, 'diamond': 5> print("The original dictionary ", test_dict1) test_dict2 = <> for key in reversed(test_dict1): test_dict2Reverse dictionary in python = test_dict1Reverse dictionary in python print("The reversed order dictionary ", test_dict2)
The original dictionary 'silver': 4, 'gold': 2, 'diamond': 5> The reversed order dictionary 'diamond': 5, 'gold': 2, 'silver': 4>

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.

Источник

How to reverse a dictionary in python?

A dictionary is a collection of key-value pairs that are ordered, mutable, and doesn’t allow redundant data. The key-value pairs in dictionaries are enclosed within a set of curly brackets <>. Consider a dictionary dict_1 = . The dictionary dict_1 when reversed is updated to .

This article discusses different approaches to reverse a dictionary in python.

Reversing a dictionary using OrderedDict() + reversed() + items()

In previous versions of python, dictionaries were not ordered. Hence, we have to convert the dictionary to OrderedDict() to preserve the order of the dictionary.

Consider a dictionary dict_1 = . The dict_1.items() returns a view object of the dictionary dict_1. The view object contains the key-value pairs of the dictionary as list of tuples.

The reversed() method is a built-in method that takes a single argument which can be any sequence like lists, tuples, dictionary, etc., and returns a reverse iterator. It doesn’t modify the original sequence. The syntax for the reversed() method is as follows.

The reversed(dict_1.items()) method reverses the item of the dictionary dict_1 and returns an iterator.

The OrderedDict() function can be imported from the collections module. The OrderDict() is a subclass of the dictionary. The OrderedDict(reversed(dict_1.items())) preserves the order of the reverse dictionary.

from collections import OrderedDict dict_1 = print("dict_1: ", dict_1) dict_2 = OrderedDict(reversed(dict_1.items())) print("dict_2: ", dict_2) 

The above code returns the output as

dict_1: dict_2: OrderedDict([(3, 'C'), (2, 'B'), (1, 'A')])

Reversing a dictionary using reversed() + items()

In the newer version of Python 3.6+, dictionaries are ordered. Hence, we don’t have to use OrderedDict() to preserve the order of a dictionary.

Consider a dictionary dict_1 = . The dict(reversed(dict_1.items())) reverses the dictionary and stores the modified dictionary in variable dict_2 = .

from collections import OrderedDict dict_1 = print("dict_1: ", dict_1) dict_2 = dict(reversed(dict_1.items())) print("dict_2: ", dict_2) 

The above code returns the output as

Reversing a dictionary using a for loop and reversed() method

Consider a dictionary dict_1 = . We declare a dictionary dict_2 initialized to an empty dictionary. A for loop iterates over the reversed dict_1 and stores the key-value pairs in dict_2.

dict_1 = print("dict_1: ", dict_1) dict_2 = <> for key in reversed(dict_1): dict_2Reverse dictionary in python = dict_1Reverse dictionary in python print("dict_2: ", dict_2) 

The above code returns the output as

Источник

Reverse A Dictionary in Python

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.

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

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 = print("The input dictionary is:") print(myDict) reversedDict = dict() for key in myDict: val = myDictReverse dictionary in python reversedDict[val] = key print("The reversed dictionary is:") print(reversedDict)
The input dictionary is: The reversed dictionary is:

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 = 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] reversedDictReverse dictionary in python = val print("The reversed dictionary is:") print(reversedDict)
The input dictionary is: The reversed dictionary is:

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 = print("The input dictionary is:") print(myDict) reversedDict = dict() for item in myDict.items(): key = item[1] val = item[0] reversedDictReverse dictionary in python = val print("The reversed dictionary is:") print(reversedDict)
The input dictionary is: The reversed dictionary is:

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 = print("The input dictionary is:") print(myDict) reversedDict = print("The reversed dictionary is:") print(reversedDict)
The input dictionary is: The reversed dictionary is:

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.

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.

Источник

Оцените статью