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} >>> for i in sorted(dict1): ## 正向排序 ... print(i, dict1[i]) ... a 40 b 80 c 30 d 20 e 60
b、逆向排序
>>> dict1 = {"c":30, "a":40, "b":80, "d":20, "e":60} ## 测试字典 >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 20, 'e': 60} >>> for i in sorted(dict1, reverse = True): ## 逆向排序 ... print(i, dict1[i]) ... e 60 d 20 c 30 b 80 a 40
。