比较字典中列表中的任何日期

时间:2018-09-13 18:30:25

标签: python list date dictionary

我有一个类似这样的日期字典(这里的键与其他工作有关,需要加以考虑):

{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.

最早的日期是2012年7月2日,所以我应该返回2

此处的注意事项:

  1. 字典中的数据是在运行时动态创建的。
  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

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

遍历字典或直接传递密钥。将列表转换为熊猫系列并对其进行排序

import pandas as pd
d={2: ['8-12-2012', '9-12-2012', '7-12-2012'], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}

for key,value in d.items():
    print(key,pd.to_datetime(pd.Series(value)).sort_values().iloc[0])

输出

(2, Timestamp('2012-07-12 00:00:00'))
(5, Timestamp('2012-10-12 00:00:00'))
(7, Timestamp('2012-12-13 00:00:00'))

如果您只关心日期

for key,value in d.items():
    print(key,pd.to_datetime(pd.Series(value)).dt.date.sort_values().iloc[0])

输出:

(2, datetime.date(2012, 7, 12))
(5, datetime.date(2012, 10, 12))
(7, datetime.date(2012, 12, 13))

按照给出的示例表示日期

for key,value in d.items():
    print('key: {}, Earliest Date: {} '.format(key,pd.to_datetime(pd.Series(value)).dt.date.sort_values().iloc[0].strftime("%m-%d-%Y")))

输出:

key: 2, Earliest Date: 07-12-2012 
key: 5, Earliest Date: 10-12-2012 
key: 7, Earliest Date: 12-13-2012 

答案 1 :(得分:2)

您可以将所有字符串转换为日期,然后使用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

答案 2 :(得分:1)

我将慢慢地解决这个问题,以便您可以看到该过程。首先,逆转命令:以时间为键,前一个键为值:

exp = {2: ['8-12-2012', '9-12-2012', '7-12-2012'], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}
rev = []

for key, val_list in exp.items():
    for val in val_list:
        rev[time.strptime(val, "%d-%m-%Y")] = key

清理表示形式,rev现在

{
    time.struct_time(tm_year=2012, tm_mon=12, tm_mday=13): 7, 
    time.struct_time(tm_year=2012, tm_mon=12, tm_mday= 8): 2, 
    time.struct_time(tm_year=2012, tm_mon=12, tm_mday= 7): 2, 
    time.struct_time(tm_year=2012, tm_mon=12, tm_mday= 9): 2, 
    time.struct_time(tm_year=2012, tm_mon=12, tm_mday=11): 5, 
    time.struct_time(tm_year=2012, tm_mon=12, tm_mday=10): 5
}

现在,尽早打印密钥很简单:

>>> rev[min(rev)]
2

如果愿意,可以将其分解为dict理解和简单的调用。