📜  Python|字典中的逆序键

📅  最后修改于: 2022-05-13 01:55:49.552000             🧑  作者: Mango

Python|字典中的逆序键

在使用字典时,有时我们可能会遇到一个问题,即我们需要以相反的顺序打印字典。让我们讨论一些可以解决这个问题的方法。

方法#1:使用reversed() + sorted() + keys() + loop
上述功能的组合可用于执行此特定任务。 sorted函数用于对键进行排序, reversed以降序获取使用keys()提取的键,这些键使用循环打印。

# 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))
输出 :
The original dictionary is : {1: 'Gfg', 2: 'best', 4: 'the', 5: 'is'}
The reversed order of dictionary keys : [5, 4, 2, 1]

方法 #2:使用list() + keys() + sorted() + reversed()
这是可以解决此任务的另一种方法。这只是上述方法的一个小变种,在此列表函数用于将结果转换为列表,而不是使用循环打印变量。

# 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))
输出 :
The original dictionary is : {1: 'Gfg', 2: 'best', 4: 'the', 5: 'is'}
The reversed order of dictionary keys : [5, 4, 2, 1]