在类别属性和今天的日期之后对字典进行排序

时间:2019-03-28 20:44:28

标签: python python-3.x

我有一个课堂,提醒和词典,活动,并想根据今天的日期对词典进行排序。

程序应要求用户输入今天的日期的int值,然后打印字典中与当天及以后相关的所有键。

例如。它不应该打印已经过去的事件。

   class Reminder:
    self.name = name
    self.date = date
    self.reminder = reminder 
    event1 = Reminder('trip to vegas', 20130312, 'buy a suitcase')
    event2 = Reminder('to do next month', 20190401, 'get a job')
    event3 = Reminder('apply for college', 20190603, 'send in application'

    event_dict = {}
    event_dict[event1.name] = event1
    event_dict[event2.name] = event2
    event_dict[event3.name] = event3

    todays date = int(input("Input today's date!"))

因此,现在当用户输入日期例如20190328时,该程序不应打印event1,因为它已经过去了。

正如我所说,我希望事件2和3在打印之前进行排序,以便首先打印下一个即将到来的日期。

似乎没有必要对2个事件进行排序,但在整个代码中将有更多事件。

2 个答案:

答案 0 :(得分:1)

简单的实现:

class Reminder:

    def __init__(self, name, date, reminder):
        self.name = name
        self.date = date
        self.reminder = reminder 

    def __str__(self):
        return "Name: '{}' - Date: '{}' - Reminder: '{}'".format(self.name,
                                                           self.date,
                                                           self.reminder)

event1 = Reminder('trip to vegas', 20130312, 'buy a suitcase')
event2 = Reminder('to do next month', 20190401, 'get a job')
event3 = Reminder('apply for college', 20190603, 'send in application')

event_dict = {}
event_dict[event1.name] = event1
event_dict[event2.name] = event2
event_dict[event3.name] = event3

todays_date = 20180101

# implementation
events_sorted = sorted(event_dict.items(), key=lambda t: t[1].date)
events = [e[1] for e in events_sorted if e[1].date >= todays_date]

for e in events:
    print(e)

输出:

Name: 'to do next month' - Date: '20190401' - Reminder: 'get a job'
Name: 'apply for college' - Date: '20190603' - Reminder: 'send in application'

答案 1 :(得分:1)

class Reminder(object):
    def __init__(self, name, date, reminder):
        self.name = name
        self.date = date
        self.reminder = reminder

event1 = Reminder('trip to vegas', 20130312, 'buy a suitcase')
event2 = Reminder('to do next month', 20190401, 'get a job')
event3 = Reminder('apply for college', 20190603, 'send in application')


event_dict = {}
    event_dict[event1.date] = event1
    event_dict[event2.date] = event2
    event_dict[event3.date] = event3

todays_date = int(input("Input today's date!"))

import operator
#filter passed dates
event_dict = {k: v for k, v in event_dict.items() if k > todays_date}

#sort dictionary
sorted_events = sorted(event_dict.items(), key=operator.itemgetter(0))

#print results
for item in sorted_events:
    print("trip name: " , item[1].name, "| trip date: ", item[1].date, "| trip reminder: ", item[1].reminder,' \n')

输出:

trip name:  to do next month | trip date:  20190401 | trip reminder:  get a job  
trip name:  apply for college | trip date:  20190603 | trip reminder:  send in application