📌  相关文章
📜  Python – 按值和键对字典进行排序

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

Python – 按值和键对字典进行排序

给定一个字典,根据降序值排序,如果值相似,则按字典顺序键。

方法:使用 sorted() + items() + 字典理解 + lambda

上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 执行排序任务,字典理解用于重新制作字典,items() 用于提取要排序的项目。

Python3
# Python3 code to demonstrate working of 
# Sort Dictionary by Values and Keys
# Using sorted() + items() + dictionary comprehension + lambda
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2, "for" : 3, "Geeks" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# - sign for descended values, omit if low-high sorting required
res = {val[0] : val[1] for val in sorted(test_dict.items(), key = lambda x: (-x[1], x[0]))}
  
# printing result 
print("Sorted dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2, 'for': 3, 'Geeks': 2}
Sorted dictionary : {'for': 3, 'is': 3, 'Best': 2, 'Geeks': 2, 'Gfg': 1}