Python | Reversed Order keys in dictionary
Last Updated :
03 May, 2023
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. The sorted function is used to sort the keys and reversed gets the keys extracted using keys(), in descending order, which are printed using a loop.
Python3
# Python3 code to demonstrate working of
# Reversed Order keys in dictionary
# Using sorted() + keys() + reversed() + loop
# initializing dictionary
test_dict = {1 : "Gfg", 5 : "is", 4 : "the", 2 : "best"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using sorted() + keys() + reversed() + loop
# Reversed Order keys in dictionary
res = []
for ele in reversed(sorted(test_dict.keys())):
res.append(ele)
# printing result
print("The reversed order of dictionary keys : " + str(res))
Output : The original dictionary is : {1: 'Gfg', 2: 'best', 4: 'the', 5: 'is'}
The reversed order of dictionary keys : [5, 4, 2, 1]
Time Complexity: O(N), where N is the length of the input string.
Auxiliary Space: O(N)
Method #2 : Using list() + keys() + sorted() + reversed() It is another method in which this task can be solved. This is just a small variation of the above method, in this the list function is used to convert the result to list rather than using the loop to print the variables.
Python3
# Python3 code to demonstrate working of
# Reversed Order keys in dictionary
# Using sorted() + keys() + reversed() + list()
# initializing dictionary
test_dict = {1 : "Gfg", 5 : "is", 4 : "the", 2 : "best"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using sorted() + keys() + reversed() + list()
# Reversed Order keys in dictionary
res = list(reversed(sorted(test_dict.keys())))
# printing result
print("The reversed order of dictionary keys : " + str(res))
Output : The original dictionary is : {1: 'Gfg', 2: 'best', 4: 'the', 5: 'is'}
The reversed order of dictionary keys : [5, 4, 2, 1]
Method #3 : Using list comprehension + keys() + sorted() + reversed()
It is also another way to perform this task, list comprehension is used to perform this task.
Python3
# Python3 code to demonstrate working of
# Reversed Order keys in dictionary
# Using sorted() + keys() + reversed() + list comprehension
# initializing dictionary
test_dict = {1 : "Gfg", 5 : "is", 4 : "the", 2 : "best"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using sorted() + keys() + reversed() + list comprehension
# Reversed Order keys in dictionary
res = [ele for ele in reversed(sorted(test_dict.keys()))]
# printing result
print("The reversed order of dictionary keys : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary is : {1: 'Gfg', 5: 'is', 4: 'the', 2: 'best'}
The reversed order of dictionary keys : [5, 4, 2, 1]
Time complexity: O(nlogn)
Auxiliary space: O(n)
Method #4: Using the heapq module
We can use the heapq.nlargest() function to get the n largest keys from the dictionary, where n is the number of items in the dictionary.
We can set n to None to get all the keys, and use the reverse=True argument to sort them in reverse order.
Python3
# import heapq module
import heapq
# initializing dictionary
test_dict = {1: "Gfg", 5: "is", 4: "the", 2: "best"}
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
# Using heapq.nlargest() to get the keys in ascending order
res = sorted(test_dict.keys(), reverse=True)
# printing result
print("The reversed order of dictionary keys: " + str(res))
OutputThe original dictionary is: {1: 'Gfg', 5: 'is', 4: 'the', 2: 'best'}
The reversed order of dictionary keys: [5, 4, 2, 1]
Time complexity: O(nlogn) for sorting the dictionary keys using heapq.nlargest(), where n is the number of items in the dictionary.
Auxiliary space: O(n) for creating a list of keys.
Similar Reads
Reverse Dictionary Keys Order - Python
We are given a dictionary and our task is to reverse the order of its keys. This means if we have a dictionary like {'a': 1, 'b': 2, 'c': 3} then the output will be {'c': 3, 'b': 2, 'a': 1}. This can be done using methods like reversed(), dictionary comprehensions, or OrderedDict. Let's explore thes
4 min read
Python - Sorted Nested Keys in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name"Then, the unique values
4 min read
Python - Sorted order Dictionary items pairing
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform reordering of dictionary items, to pair key and values in sorted order, smallest pairing to smallest value, largest to largest value and so on. This kind of application can occur in competitive domain
3 min read
Remove Spaces from Dictionary Keys - Python
Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'fir
3 min read
Add Same Key in Python Dictionary
The task of adding the same key in a Python dictionary involves updating the value of an existing key rather than inserting a new key-value pair. Since dictionaries in Python do not allow duplicate keys, adding the same key results in updating the value of that key. For example, consider a dictionar
3 min read
How to Reverse a Dictionary in Python
Reversing a dictionary typically means swapping the keys and values, where the keys become the values and the values become the keys. In this article, we will explore how to reverse a dictionary in Python using a variety of methods.Using Dictionary ComprehensionDictionary comprehension is a concise
2 min read
Remove Kth Key from Dictionary - Python
We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
3 min read
Python | N largest values in dictionary
Many times while working with a Python dictionary, we can have a particular problem finding the N maxima of values in numerous keys. This problem is quite common while working in the web development domain. Let's discuss several ways in which this task can be performed. Method #1 : itemgetter() + it
5 min read
Minimum Value Keys in Dictionary - Python
We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
4 min read