001、
>>> dict1 = {"d":400, "a":300, "e":500, "b":700, "c":600} ## 测试字典 >>> dict1 {'d': 400, 'a': 300, 'e': 500, 'b': 700, 'c': 600} >>> sorted(dict1.keys()) ## 对字典的键进行排序 ['a', 'b', 'c', 'd', 'e'] >>> sorted(dict1.values()) ## 对字段的值进行排序 [300, 400, 500, 600, 700]
002、
>>> dict1 = {"d":400, "a":300, "e":500, "b":700, "c":600} ## 测试字典 >>> dict1 {'d': 400, 'a': 300, 'e': 500, 'b': 700, 'c': 600} >>> sorted(dict1.items(), key = lambda x: x[0]) ## 依据字典的键,对项进行排序 [('a', 300), ('b', 700), ('c', 600), ('d', 400), ('e', 500)] >>> sorted(dict1.items(), key = lambda x: x[1]) ## 依据字典的值,对项进行排序 [('a', 300), ('d', 400), ('e', 500), ('c', 600), ('b', 700)] >>> sorted(dict1.items(), key = lambda x: x[0], reverse = True) ## 增加reverse = True; 逆向排序 [('e', 500), ('d', 400), ('c', 600), ('b', 700), ('a', 300)] >>> sorted(dict1.items(), key = lambda x: x[1], reverse = True) [('b', 700), ('c', 600), ('e', 500), ('d', 400), ('a', 300)]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280174.html