【发布时间】:2018-09-13 18:30:24
【问题描述】:
我有一个这样的日期字典(这里的键与其他一些工作相关,需要考虑):
{2: ['8-12-2012', '9-12-2012', '7-12-2012],
5: ['10-12-2012', '11-12-2012'],
7: ['13-12-2012']}
现在,我想在每个列表中找到最早的日期。最后,我需要找出最早的日期,并返回那个日期和密钥。
如果我在这里手动完成我想要做的事情:
**key 2**, `7-12-2012` is the earliest.
**key 5**, `10-12-2012` is the earliest.
**key 7**, `13-12-2012` is the earliest.
7-12-2012 是最早的日期,所以我应该返回2。
注意事项:
- 字典中的数据是在运行时动态创建的。
- 字典中的列表不是固定长度的。
这是我尝试过的,但只比较两个日期:
...
...
# this value would be dynamically set during runtime
expiryDates[item] = {2: ['8-12-2012', '9-12-2012', '7-12-2012], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}
datesInBox = []
dict_earliest_expiration = defaultdict(list)
for n in expiryDates:
datesInBox = expiryDates[n] # when n = 2; datesInBox = ['8-12-2012', '9-12-2012']
d1 = time.strptime(datesInBox[0], "%d-%m-%Y")
d2 = time.strptime(datesInBox[1], "%d-%m-%Y")
if d1 < d2:
dict_earliest_expiration[n] = d1
else:
dict_earliest_expiration[n] = d2
任何帮助将不胜感激。
【问题讨论】:
标签: python list date dictionary