我有一个这样的日期字典(这里的键与其他一些工作相关,需要考虑):
{2: ['8-12-2012', '9-12-2012', '7-12-2012],
5: ['10-12-2012', '11-12-2012'],
7: ['13-12-2012']}
现在,我想在每个列表中找到最早的日期。最后,我需要找出所有日期中最早的日期,并返回该日期和 key 。
如果我手动完成我在这里尝试做的事情:
**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
如有任何帮助,我们将不胜感激。
请您参考如下方法:
您可以将所有字符串转换为日期,然后使用 min功能:
import time
data = {2: ['8-12-2012', '9-12-2012', '7-12-2012'], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}
d2 = {k: [time.strptime(e, "%d-%m-%Y") for e in v] for k, v in data.items()}
print(min(d2, key=lambda e: min(d2[e])))
输出
2
作为替代方案,您可以预先计算字典中每个键的最小值:
data = {2: ['8-12-2012', '9-12-2012', '7-12-2012'], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}
d2 = {k: min(time.strptime(e, "%d-%m-%Y") for e in v) for k, v in data.items()}
print(min(d2, key=lambda e: d2[e]))
输出
2
最后,您可以遍历键值对,而不是遍历键:
data = {2: ['8-12-2012', '9-12-2012', '7-12-2012'], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}
d2 = {k: min(time.strptime(e, "%d-%m-%Y") for e in v) for k, v in data.items()}
print(min(d2.items(), key=lambda t: t[1])[0])
输出
2
