python 中 实现按照字典的键和值进行排序

 

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)]

 

>>> 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)]
>>> dict(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)]
>>> dict(sorted(dict1.items(), key = lambda x: x[1]))              ## 依据字典的值进行排序, 并返回字典
{'a': 300, 'd': 400, 'e': 500, 'c': 600, 'b': 700}

 

003、

>>> dict1 = {"d":400, "a":300, "e":500, "b":700, "c":600}   
>>> dict2 = {}
>>> for i in sorted(dict1):                                    依据键进行排序
...     dict2[i] = dict1[i]
...
>>> dict2
{'a': 300, 'b': 700, 'c': 600, 'd': 400, 'e': 500}

 

004、借助于import operator 包

>>> dict1 = {"d":400, "a":300, "e":500, "b":700, "c":600}          ## 测试字典
>>> dict1
{'d': 400, 'a': 300, 'e': 500, 'b': 700, 'c': 600}
>>> import operator                                                ## 导入包
>>> dict(sorted(dict1.items(), key=operator.itemgetter(0)))        ## 依据字典的键进行排序
{'a': 300, 'b': 700, 'c': 600, 'd': 400, 'e': 500}
>>> dict(sorted(dict1.items(), key=operator.itemgetter(1)))        ## 依据字典的值进行排序
{'a': 300, 'd': 400, 'e': 500, 'c': 600, 'b': 700}

 

posted @ 2022-08-12 20:15  小鲨鱼2018  阅读(94)  评论(0编辑  收藏  举报