+

Python | Reverse order of keys in a dictionary

Method # 1: Using reversed () + sorted () + keys () + loop
A combination of the above functions can be used to accomplish this particular task. The sorted function is used to sort the keys, and in reversed , the keys are retrieved using keys () in descending order, which are printed using a loop.

Output:

 The original dictionary is: {1: `Gfg`, 2:` best`, 4: `the`, 5 : `is`} The reversed order of dictionary keys: [5, 4, 2, 1] 

Method # 2: Using list () + keys () + sorted () + reversed ()
This is another method by which this task can be accomplished. This is just a slight variation of the above method, in which case the list function is used to convert the result to a list rather than using a loop to print variables.

# Python3 code to demonstrate how it works
# Reverse order of keys in the dictionary
# Using sorted () + keys () + reversed () + loop

 
# initializing dictionary

test_dict = { 1 : "Gfg " , 5 : " is " , 4 : "the" , 2 : "best" }

 
# print original dictionary

print ( "The original dictionary is:" + str (test_dict))

 
# Using sorted () + keys () + reversed () + loop
# Reverse order of keys in the dictionary

res = []

for ele in reversed ( sorted (test_dict.keys ())):

res.append (ele)

 
# print result

print ( "The reversed order of dictionary keys:" + str (res))

# Python3 demo code
# Reverse order of keys in the dictionary
# Using sorted () + keys ( ) + reversed () + list ()

 
# initializing dictionary

test_dict = { 1 : "Gfg" , 5 : "is" , 4 : "the" , 2 : "best" }

 
# print original dictionary

print ( " The original dictionary is: " + str (test_dict))

  
# Using sorted () + keys () + reversed () + list ()
# Reverse order of keys in the dictionary

res = list ( reversed ( sorted (test_dict.keys ())))

  
# print 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] 
Get Solution for free from DataCamp guru