Open In App

Python – Reverse Dictionary Keys Order

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Similar Reads

Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python | Reversed Order keys in dictionary
While working with dictionary, we can sometimes, have a problem in which we require to print dictionaries in the reversed order of their occurrence. Let's discuss certain ways in which this problem can be solved. Method #1 : Using reversed() + sorted() + keys() + loop The combination of above functions can be used to perform this particular task. T
4 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Python - Cumulative Mean of Dictionary keys
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys. Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12}, {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}] Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5,
6 min read
Python Dictionary keys() method
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Syntax: dict.keys() Parameters: There are no parameters. Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary. Method 1
2 min read
Practice Tags :