简体   繁体   中英

Printing entries in a dictionary in descending order

Printing entries in a dictionary in descending order so that I can view them according to the example

08:02 - registration

08:45 - doctor checkup

09:00 - procedure

09:15 - doctor checkup

09:25 - radiography

10:30 - blood test

11:00 - doctor checkup

11:30 - hospital discharge

class Time():
    def __init__(self, hour, minutes):
        self.hour = hour
        self.minutes = minutes

    def __str__(self):
        return "%02d:%02d" % (self.hour, self.minutes)

    def __repr__(self):
        if self.minutes == 0:
            return 'Time({0},{1}0)'.format(self.hour, self.minutes)
        return 'Time({0},{1})'.format(self.hour, self.minutes)
    
class Event():
    def __init__(self, time, nameStattion):
        self.time = time
        self.nameStattion = nameStattion

    def __str__(self):
        return "{0}-{1}".format(self.time, self.nameStattion)

    def __repr__(self):
        return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)
    
class MedicalRecord():
    data = {}

    def __init__(self, name, id):
        self.name = name
        self.id = id

    def __repr__(self):
       return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)

    def add(self, time, station):
        self.data[time] = Event(Time(int(time[0:2]), int(time[3:5])), station)

    def view(self):
        #for i in range(len(self.data)):
            print(eval(repr(self.data)))

time1 = Time(8, 2)
time1
print(time1)
time2 = eval(repr(time1))
print(time2)
event1 = Event(time1, 'registration')
event1
event2 = eval(repr(event1))
print(event2)
record1 = MedicalRecord('David', 1)
record1.add('08:02', 'registration')
print(record1.data)
record1.add('09:15','doctor checkup')
record1.add('08:45','doctor checkup')
record1.add('09:00','procedure')
record1.add('11:00','doctor checkup')
record1.add('09:25','radiography')
record1.add('11:30','hospital discharge')
record1.add('10:30','blood test')
record1.view()

In my example it prints as one side list

You would want to use the python sorted() function. It will have a key argument which you can pass a function that returns the time and python will sort the list according to that. From there you will probably get an ascending list which you can just do list.reverse() to make it descending.

Edit: actully sorted lets you choose if its acending or decending using the "reverse" argument. See the sorted link for more info.

def keyFunc(EventObj): return f'{EventObj.time}' 
sortedList = sorted(SomeEventList, key=keyFunc, reversed = True)
    def view(self):
        for key in sorted(self.data):
            print(key, '-', self.data[key])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM