Python – 按值和键对字典进行排序
给定一个字典,根据降序值排序,如果值相似,则按字典顺序键。
Input : test_dict = {“gfg” : 1, “is” : 1, “best” : 1, “for” : 1, “geeks” : 1}
Output : {“best” : 1, “is” : 1, “for” : 1, “geeks” : 1, “gfg” : 1}
Explanation : All values are equal, hence lexicographically sorted keys.
Input : test_dict = {“gfg” : 5, “is” : 4, “best” : 3, “for” : 2, “geeks” : 1}
Output : {“gfg” : 5, “is” : 4, “best” : 3, “for” : 2, “geeks” : 1}
Explanation : All values are different, hence descending ordered sorted.
方法:使用 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}