Chiranjeeb
I believe the problem you're having is that your list 'L' contains the strings appended in the first for loop, and tuples appended in the third for loop. So, when you try to sort it, it isn't sure how to compare strings with tuples. You can fix it by resetting the L list just before the third for loop with L = [] or L.clear().
Also note that when posting code on the forum, you can wrap it with ``` at the start and end to keep the code formatting.
file = open('mbox-short.txt')
D=dict()
L=list()
for line in file:
line = line.rstrip()
if line.startswith('From'):
timeofday = line.split()
if len(timeofday)>3:
pos=timeofday[5].find(':')
hour=timeofday[5][:pos]
L.append(hour)
for x in L:
D[x]= D.get(x,0)+1
L.clear()
for key,val in list(D.items()):
L.append((key,val))
L.sort()
for k,v in L:
print (k,v)
All the best,