如何按日期时间键对python字典进行排序?

时间:2016-12-16 10:12:17

标签: python dictionary

我有一个如下字典:

dt = {'2016-12-15 18:12:17': 1, '2016-12-15 17:40:39': 1, '2016-12-15 15:53:42': 1, '2016-12-15 15:51:41': 1, '2016-12-15 15:49:55': 1, '2016-12-15 15:49:54': 1, '2016-12-15 15:48:05': 1, '2016-12-15 15:27:38': 1, '2016-12-15 09:05:03': 1, '2016-12-15 08:43:45': 1, '2016-12-15 07:29:15': 1, '2016-12-15 05:56:58': 1, '2016-12-14 14:33:31': 1, '2016-12-14 14:33:30': 1, '2016-12-14 14:33:29': 1, '2016-12-14 14:33:28': 1, '2016-12-14 13:24:55': 1, '2016-12-14 13:15:51': 1, '2016-12-14 13:05:38': 1, '2016-12-14 12:58:47': 1}

我想在datetime键上对字典进行排序。

我试过了:

dt = ordereddict.OrderedDict()

但它没有用,请帮助。

1 个答案:

答案 0 :(得分:4)

dt中的密钥转换为datetime个对象,例如,使用dateutil.parser.parse

from dateutil.parser import parse
from collections import OrderedDict

new_d = OrderedDict(sorted(dt.items(), key=lambda x: parse(x[0])))

print(new_d)
'''
OrderedDict([   ('2016-12-14 12:58:47', 1), 
                ('2016-12-14 13:05:38', 1), 
                ('2016-12-14 13:15:51', 1), 
                ('2016-12-14 13:24:55', 1), 
                ('2016-12-14 14:33:28', 1), ('2016-12-14 14:33:29', 1), ('2016-12-14 14:33:30', 1), ('2016-12-14 14:33:31', 1), ('2016-12-15 05:56:58', 1), ('2016-12-15 07:29:15', 1), ('2016-12-15 08:43:45', 1), ('2016-12-15 09:05:03', 1), ('2016-12-15 15:27:38', 1), ('2016-12-15 15:48:05', 1), ('2016-12-15 15:49:54', 1), ('2016-12-15 15:49:55', 1), ('2016-12-15 15:51:41', 1), ('2016-12-15 15:53:42', 1), ('2016-12-15 17:40:39', 1), ('2016-12-15 18:12:17', 1)])

'''

在你的特定情况下,正如@AndreaCorbellini指出的那样,直接排序字符串工作正常,即

new_d = OrderedDict(sorted(dt.items()))