Sort Python dict by datetime value
This question already has an answer here:
You could sort the keys like this:
sorted(dct, key=dct.get)
See the Sorting Mini-HOW TO for an explanation of this and other techniques for sorting.
Bearing in mind that the question asks how to sort by the datetime values, here's a possible answer:
sorted(dct.items(), key=lambda p: p[1], reverse=True)
=> [('raspberry', datetime.datetime(2013, 1, 9, 0, 0)),
('apple', datetime.datetime(2012, 12, 20, 0, 0)),
('orange', datetime.datetime(2012, 2, 4, 0, 0))]
If you're only interested in the keys:
[k for k, v in sorted(dct.items(), key=lambda p: p[1], reverse=True)]
=> ['raspberry', 'apple', 'orange']
这很简单,你只需要做,就像:
from operator import itemgetter
sorted(a.items(),key=itemgetter(1),reverse=True)
链接地址: http://www.djcxy.com/p/18154.html
上一篇: 按值排序字典并返回字典,而不是元组列表
下一篇: 按日期时间值对Python字典进行排序