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)
Comments (3)
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))
Last Modified: Feb. 27, 2008
Author: James Tauber
blah on Feb. 27, 2008:
s/doh/duh/