Python – Reverse Dictionary Keys Order
Last Updated :
25 Apr, 2023
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
from collections import OrderedDict
test_dict = { 'gfg' : 4 , 'is' : 2 , 'best' : 5 }
print ("The original dictionary : " + str (test_dict))
res = OrderedDict( reversed ( list (test_dict.items())))
print ("The reversed order dictionary : " + str (res))
|
Output :
The original dictionary : {‘is’: 2, ‘best’: 5, ‘gfg’: 4} The reversed order dictionary : OrderedDict([(‘gfg’, 4), (‘best’, 5), (‘is’, 2)])
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
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
test_dict = { 'gfg' : 4 , 'is' : 2 , 'best' : 5 }
print ("The original dictionary : " + str (test_dict))
res = dict ( reversed ( list (test_dict.items())))
print ("The reversed order dictionary : " + str (res))
|
Output :
The original dictionary : {'gfg': 4, 'is': 2, 'best': 5}
The reversed order dictionary : {'best': 5, 'is': 2, 'gfg': 4}
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.
Python3
from collections import OrderedDict, deque
def reverse_dict_keys_order(test_dict):
keys_deque = deque(test_dict.keys())
keys_deque.reverse()
new_dict = {key: test_dict[key] for key in keys_deque}
new_ordered_dict = OrderedDict(new_dict)
return new_ordered_dict
test_dict = { 'is' : 2 , 'gfg' : 4 , 'best' : 5 }
print (reverse_dict_keys_order(test_dict))
|
Output
OrderedDict([('best', 5), ('gfg', 4), ('is', 2)])
Time Complexity: O(n) – iterating through the dictionary keys takes n time complexity.
Space Complexity: O(n) – creating a new dictionary object, a deque object, and an OrderedDict object.
Method #4 :Using a loop and pop() to remove and re-add key-value pairs:
Algorithm :
1. Create an empty dictionary called reversed_dict.
2. While the input dictionary test_dict is not empty:
a. Pop the last item (key-value pair) from test_dict.
b. Add the popped item to reversed_dict with the key-value pair reversed.
3. Print the reversed dictionary reversed_dict.
Python3
test_dict = { 'gfg' : 4 , 'is' : 2 , 'best' : 5 }
print ( "The original dictionary : " + str (test_dict))
reversed_dict = {}
while test_dict:
key, value = test_dict.popitem()
reversed_dict[key] = value
print ( "The reversed order dictionary : " + str (reversed_dict))
|
Output
The original dictionary : {'gfg': 4, 'is': 2, 'best': 5}
The reversed order dictionary : {'best': 5, 'is': 2, 'gfg': 4}
Time complexity: The while loop executes n times, where n is the number of key-value pairs in the input dictionary. The popitem() method has a time complexity of O(1) on average, so the time complexity of this algorithm is O(n).
Space complexity: We create an empty dictionary called reversed_dict, which has a space complexity of O(1). We also pop n key-value pairs from test_dict and add them to reversed_dict, which has a space complexity of O(n). Therefore, the overall space complexity of this algorithm is O(n).
Method #6: Using the sorted() function and a lambda function
- Use the sorted() function to sort the dictionary keys in reverse order, based on their original position in the list of keys (list(test_dict.keys()).index(x)).
- Use a dictionary comprehension to create a new dictionary with the sorted keys and original values.
Python3
test_dict = { 'gfg' : 4 , 'is' : 2 , 'best' : 5 }
print ( "The original dictionary : " + str (test_dict))
res = {k: test_dict[k] for k in sorted (test_dict, key = lambda x: list (test_dict.keys()).index(x), reverse = True )}
print ( "The reversed order dictionary : " + str (res))
|
Output
The original dictionary : {'gfg': 4, 'is': 2, 'best': 5}
The reversed order dictionary : {'best': 5, 'is': 2, 'gfg': 4}
Time complexity: O(n log n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the sorted list of keys and the new dictionary.
Please Login to comment...