Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何按datetime键对python字典排序?_Python_Dictionary - Fatal编程技术网

如何按datetime键对python字典排序?

如何按datetime键对python字典排序?,python,dictionary,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,

我有一本字典如下:

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

但它不起作用,请帮助。

dt
中的键转换为对象,例如,使用


在您的特定情况下,正如@AndreaCorbellini所指出的,直接对字符串进行排序很好,即

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

dt
中的键转换为对象,例如,使用


在您的特定情况下,正如@AndreaCorbellini所指出的,直接对字符串进行排序很好,即

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

有序dict保持插入顺序,它不按值对键进行排序,此外,还具有字符串而不是日期时间。您必须自己对密钥进行排序,并生成一个新的有序dict。是的,
orderedict.orderedict()
本身做不了什么。“不起作用”到底是什么意思?错误?还有比这更多的代码吗?通过
dt.keys()
获取密钥并对它们进行排序。然后按键访问值。
ordered=OrderedDict(排序(mydict.items(),key=lambda t:t[0])
OrderedDict保持插入顺序,它不按值排序键,此外,还有字符串而不是日期时间。您必须自己对密钥进行排序,并生成一个新的有序dict。是的,
orderedict.orderedict()
本身做不了什么。“不起作用”到底是什么意思?错误?还有比这更多的代码吗?通过
dt.keys()
获取密钥并对它们进行排序。然后通过键访问值。
ordered=OrderedDict(排序(mydict.items(),key=lambda t:t[0])
+1,只需一句话:不需要转换到
datetime
:以该格式编写的字符串排序只需fine@AndreaCorbellini,谢谢你指出这一点,我只是把它添加到我的答案中。+1,请注意:不需要转换为
datetime
:以该格式编写的字符串排序只需fine@AndreaCorbellini,谢谢你指出这一点,我只是把它添加到我的答案中。