字典排序问题

2018-01-03@望京

排序,立即想到用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(默认值);

 

Py2中使用sort的cmp参数自定义排序方式

>>> 
>>> res = [{'name':'hi','age':10},{'name':None,'age':10},{'name':'bo','age':10},{'name':'aaa','age':10}]
>>> 
>>> res.sort(cmp=lambda x, y: cmp(x['name'], y['name']))
>>> 
>>> res
[{'age': 10, 'name': None}, {'age': 10, 'name': 'aaa'}, {'age': 10, 'name': 'bo'}, {'age': 10, 'name': 'hi'}]
>>> 

 

使用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')]
>>> 

  

转载于:https://www.cnblogs.com/standby/p/8269276.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值