James Tauber

journeyman of some

blog > 2008 > 02 > 27 >

Another Dictionary Trick

Continuing on from my previous post about python dictionaries.

Imagine you're using a defaultdict to count objects. That is, you set up like this:

from collections import defaultdict
counts = defaultdict(int)

and then have a bunch of these for different keys:

counts[key] += 1

Now say you want a list of all the objects in order of their count, like I did earlier this morning. My first intuition was to use

sorted(counts, key=lambda i: counts[i])

which then got me wondering if there was a way to create a function that gets an item from dictionary without using lambda—much the same way as the operator module can be used instead of lambdas in many cases.

Then I had a doh! moment. Of course there's a function that gets an item from a dictionary: the get method. And so the above can be rewritten:

sorted(counts, key=counts.get)

Categories:
prev « python » next

Comments (3)

blah on Feb. 27, 2008:

s/doh/duh/

James Tauber on Feb. 27, 2008:

No, blah, I mean 'doh!' although 'duh!' is also appropriate.

Justin on Feb. 27, 2008:

I've seen things like this on more than one occasion, this is the real doh!:

sorted(counts,key=lambda k:counts.get(k))

Add a Comment

Created: Feb. 27, 2008
Last Modified: Feb. 27, 2008
Author: jtauber