Sort by key, then by content

W

Wayne Folta

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,498
Latest member
log5Sshell/alfa5

Latest Threads

Top