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)

The original post was in the category: python but I'm still in the process of migrating categories over.

The original post had 3 comments I'm in the process of migrating over.