如何在字典中对日期和时间列表进行排序?

2024-09-30 20:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本有3个键的字典,它们的值是日期和时间的列表。我试图将日期和时间的列表从最早的到最新的进行排序,但我不确定如何对它们进行排序。有没有一种简单快捷的方法来对这些日期和时间列表进行排序

commits_dict = {
    'Jordan McCullough': ['2014-11-07, 18:27:19', '2014-11-05, 20:00:35', '2014-11-05, 19:59:55'],
    'Peter Bell': ['2013-06-18, 19:34:38', '2014-11-05, 15:33:57'],
    'Matthew McCullough': ['2012-08-31, 20:35:43', '2012-08-31, 00:00:50', '2012-07-25, 05:25:20']
}

Tags: 方法列表字典排序时间dictpetercommits
1条回答
网友
1楼 · 发布于 2024-09-30 20:20:30

您可以使用每个字符串的datetime值作为键,并从最早到最新排序:

import datetime

commits_dict = {
    'Jordan McCullough': ['2014-11-07, 18:27:19', '2014-11-05, 20:00:35', '2014-11-05, 19:59:55'],
    'Peter Bell': ['2013-06-18, 19:34:38', '2014-11-05, 15:33:57'],
    'Matthew McCullough': ['2012-08-31, 20:35:43', '2012-08-31, 00:00:50', '2012-07-25, 05:25:20']
}


def key(s):
    return datetime.datetime.strptime(s, '%Y-%m-%d, %H:%M:%S')


result = {k: sorted(v, key=key) for k, v in commits_dict.items()}

print(result)

输出

{'Jordan McCullough': ['2014-11-05, 19:59:55', '2014-11-05, 20:00:35', '2014-11-07, 18:27:19'], 'Peter Bell': ['2013-06-18, 19:34:38', '2014-11-05, 15:33:57'], 'Matthew McCullough': ['2012-07-25, 05:25:20', '2012-08-31, 00:00:50', '2012-08-31, 20:35:43']}

相关问题 更多 >