Sort by key, then by content

Sean 'Shaleh' Perry shaleh at speakeasy.net
Fri Jan 30 08:48:57 CET 2004


On Thursday 29 January 2004 23:12, Wayne Folta wrote:
> 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...
>
>
> Any suggestions?

How's this?

>>> d = {'shaleh@': ['Sean Perry', 12], 'lesley@': ['Lesley Perry', 34], 
'dean@': ['Dean Perry', 100]}
>>> contents = zip(d.keys(), d.values())
>>> contents.sort()
>>> contents
[('dean@', ['Dean Perry', 100]), ('lesley@', ['Lesley Perry', 34]), 
('shaleh@', ['Sean Perry', 12])]
>>> contents.sort(lambda x,y: cmp(x[1][1], y[1][1]))
>>> contents
[('shaleh@', ['Sean Perry', 12]), ('lesley@', ['Lesley Perry', 34]), ('dean@', 
['Dean Perry', 100])]





More information about the Python-list mailing list