字典排序问题

Posted 青山应回首

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典排序问题相关的知识,希望对你有一定的参考价值。

[email protected]望京

排序,立即想到用Python的内置函数sorted()

Python 2.x 中
sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list


Python 3.x 中
sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customise the sort order, and the
    reverse flag can be set to request the result in descending order.

 

字典按key排序

>>> dic = {‘a‘:9, ‘c‘:3, ‘f‘:12, ‘b‘:1, ‘d‘:7}
>>> 
>>> sorted(dic)
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘f‘]
>>> 
>>> sorted(dic.keys())
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘f‘]
>>> 
>>> sorted(dic.values())
[1, 3, 7, 9, 12]
>>> 
>>> sorted(dic.items())
[(‘a‘, 9), (‘b‘, 1), (‘c‘, 3), (‘d‘, 7), (‘f‘, 12)]
>>>
>>> for k in sorted(dic):
...     print dic[k]
... 
9
1
3
7
12
>>>

 

字典是无序的,对字典排序本身是一个没有太大意义的事,但是面试的时候总会遇到==‘‘

那么问题来了,如何对字典按照value排序呢(默认是对key进行排序)?

首先需要知道sorted()这个函数的几个参数的意思(按照Python 3.x来说明):

    - iterable   指的是可迭代对象,可以是dic,dic.items(), dic.keys(),  dic.values() 等等;

    - key         key对应一个函数,用来选取参与比较的元素;

    - reverse   排序规则. reverse = True 或者 reverse = False(默认值);

 

使用key参数来实现

items()方法将字典的元素 转化为了元组

>>> dic
{‘a‘: 9, ‘c‘: 3, ‘b‘: 1, ‘d‘: 7, ‘f‘: 12}
>>> dic.items()
[(‘a‘, 9), (‘c‘, 3), (‘b‘, 1), (‘d‘, 7), (‘f‘, 12)]
>>> 
>>> sorted(dic.items())
[(‘a‘, 9), (‘b‘, 1), (‘c‘, 3), (‘d‘, 7), (‘f‘, 12)]
>>> 
>>> sorted(dic.items(), key=lambda x:x[1])
[(‘b‘, 1), (‘c‘, 3), (‘d‘, 7), (‘a‘, 9), (‘f‘, 12)]
>>> 

 

使用zip来实现

>>> dic
{‘a‘: 9, ‘c‘: 3, ‘b‘: 1, ‘d‘: 7, ‘f‘: 12}
>>> 
>>> new_dic = zip(dic.values(), dic.keys())
>>> 
>>> new_dic
[(9, ‘a‘), (3, ‘c‘), (1, ‘b‘), (7, ‘d‘), (12, ‘f‘)]
>>> 
>>> sorted(new_dic)
[(1, ‘b‘), (3, ‘c‘), (7, ‘d‘), (9, ‘a‘), (12, ‘f‘)]
>>> 

  

以上是关于字典排序问题的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

什么是字典排序

Python代码阅读(第40篇):通过两个列表生成字典

Python:按多个条件显示排序字典

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段