dxb625
dxb625

Reputation: 63

sort by days of the week after email line split

I have a code that retrieves mbox.txt and splits the From line to obtain days of the week and counts how often the day appears. I managed to do that but now I am stuck on how to sort the list according to the days of the week.

filename = input("Please Enter A File Name: ")
filehand = open (filename)
count=dict()
for line in filehand:
    if not line.startswith('From ') : continue 
    line = line.split() 
    day = line[2]  

    count[day] = count.get(day,0)+1

Flist = list()
for key, value in count.items():
    Flist.append((key, value))
Flist.sort(key = lambda l: (l[1], l[0]), )

for key, value in Flist:
     print (key, value)

My output:

Please Enter A File Name: mbox.txt
Sat 61
Sun 66
Wed 292
Mon 299
Fri 315
Tue 372
Thu 392

Is there a way I can get it to appear like the list below?

Mon 299
Tue 372
Wed 292
Thu 392
Fri 315
Sat 66
Sun 61

Upvotes: 0

Views: 38

Answers (2)

accdias
accdias

Reputation: 5372

As suggested, use collections.OrderedDict():

from collections import OrderedDict

weekdays = OrderedDict({
    'Mon': 0,
    'Tue': 0,
    'Wed': 0,
    'Thu': 0,
    'Fri': 0,
    'Sat': 0,
    'Sun': 0})

filename = input("Please Enter A File Name: ")
with open(filename) as f:
    for line in f:
        if line.startswith('From '): 
            line = line.strip().split() 
            weekdays[line[2]] += 1  

for weekday, count in weekdays.items():
    print(weekday, count)

Upvotes: 1

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

Instead of this :

Flist.sort(key = lambda l: (l[1], l[0]), )

Try this :

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

Flist = sorted(Flist, key= lambda l : days.index(l[0]))
# Or,
Flist.sort(key = lambda l: days.index(l[0]))

Upvotes: 1

Related Questions