Sort by key, then by content

Wayne Folta wfolta at netmail.to
Fri Jan 30 08:12:03 CET 2004


As an experiment, I've written a Python script which reads my mailboxes 
and prints a report on how many messages I've gotten from from each 
unique sender. I use a dictionary with a key of the email address and 
each entry is a list with the 0th element being the user's name (if 
known) and the 1st being the count.

At the end, I print the report, sorted by email address. But then I 
want to print it sorted by frequency of message. What would be the most 
efficient, idiomatic, iterative, functional way to do that. After some 
head-twisting (it's way past my bedtime), I finally figured that 
heapq's would help me, but it seems there should be a cool way to turn 
the dict into a list (map) and also turn it inside out at the same 
time...

keys = addr_dict.keys ()
keys.sort ()
heap = []

for k in keys:
         print "%s (%s)\t%d" % (k, addr_dict[k][0], addr_dict[k][1])
         heapq.heappush (heap, (addr_dict[k][1], k, addr_dict[k][0]))

print '*' * 80
while (heap):
         print "%d\t%s (%s)" % heapq.heappop (heap)

Any suggestions?





More information about the Python-list mailing list