Warm tip: This article is reproduced from serverfault.com, please click

其他-python函数。

(其他 - python function. output a keys list from a dictionary if the key is todays date)

发布于 2020-11-27 23:55:54

我导入datetime模块。但我不确定如何将其称为字典键。

def bad_food():
    today = datetime.date.today()
    past_due = {
        datetime.date.today(2020,11,24): ['chicken' , 'soup', 'chips'],
        datetime.date.today(2020,11,27) : ['lays', 'chilli'],
                }
    for key in past_due:
        if key == today:
            print (today.values())
print(bad_food())```
Questioner
Dane Cantrell
Viewed
11
Sash Sinha 2020-11-28 08:17:04

你可以将为每个键提供的信息元组(即和)进行比较yearmonth并将date其与来自的可用信息的相同子集进行比较today

>>> import datetime
>>>
>>> def bad_food():
...     today = datetime.datetime.now()
...     past_due = {
...         datetime.datetime(2020, 11, 24): ['chicken', 'soup', 'chips'],
...         datetime.datetime(2020, 11, 27): ['lays', 'chilli'],
...     }
...     for key in past_due:
...         if (key.year, key.month, key.day) == (today.year, today.month, today.day):
...             print(past_due[key])
...
>>> bad_food()
['lays', 'chilli']