Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Reverse Dictionary Keys Order

Python – Reverse Dictionary Keys Order

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




# Python3 code to demonstrate working of
# Reverse Dictionary Keys Order
# Using OrderedDict() + reversed() + items()
from collections import OrderedDict
 
# initializing dictionary
test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Reverse Dictionary Keys Order
# Using OrderedDict() + reversed() + items()
res = OrderedDict(reversed(list(test_dict.items())))
 
# printing result
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




# Python3 code to demonstrate working of
# Reverse Dictionary Keys Order
# Using reversed() + items()
 
# initializing dictionary
test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Reverse Dictionary Keys Order
# Using reversed() + items()
res = dict(reversed(list(test_dict.items())))
 
# printing result
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 #import deque
 
def reverse_dict_keys_order(test_dict):#define input
    keys_deque = deque(test_dict.keys())#get keys
    keys_deque.reverse()#reverse the keys
    new_dict = {key: test_dict[key] for key in keys_deque}#assign values to the key
    new_ordered_dict = OrderedDict(new_dict)#assign to new dict
    return new_ordered_dict#return result
 
test_dict={'is': 2, 'gfg': 4,'best': 5}#input
print(reverse_dict_keys_order(test_dict))#print output


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}
# printing original dictionary
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))
 
#This code is contributed by Jyothi pinjala.


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




# Python3 code to demonstrate working of
# Reverse Dictionary Keys Order
# Using sorted() and lambda
 
# initializing dictionary
test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Reverse Dictionary Keys Order
# Using sorted() and lambda
res = {k: test_dict[k] for k in sorted(test_dict, key=lambda x: list(test_dict.keys()).index(x), reverse=True)}
 
# printing result
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.

RELATED ARTICLES

Most Popular

Recent Comments