python中依据字典的值进行排序
001、依据字典的值对字典进行排序
a、正向排序
>>> dict1 = {"c":30, "a":40, "b":80, "d":20, "e":60} ## 测试字典 >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 20, 'e': 60} >>> sorted(dict1.values()) [20, 30, 40, 60, 80] >>> for i in sorted(dict1.values()): ## 依据字典的值进行正向排序 ... for j,k in dict1.items(): ... if i == k: ... print(j,k) ... d 20 c 30 a 40 e 60 b 80
b、逆向排序
>>> dict1 = {"c":30, "a":40, "b":80, "d":20, "e":60} ## 测试字典 >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 20, 'e': 60} >>> sorted(dict1.values()) [20, 30, 40, 60, 80] >>> sorted(dict1.values(), reverse = True) [80, 60, 40, 30, 20] >>> for i in sorted(dict1.values(), reverse = True): ## 依据字典的值进行逆向排序 ... for j,k in dict1.items(): ... if k == i: ... print(j, k) ... b 80 e 60 a 40 c 30 d 20
。