James Tauber's Blog 2008/02/27
Google Summer of Code 2008
Well, the Google Summer of Code is on again and the Python Software Foundation have asked me to coordinate for the second year (mustn't have screwed up enough last year :-)
It's early days (the organizations involved haven't even been picked yet) but if you are interested in participating in a Python project, either as a mentor or student, you should check out both the official Google page and the SummerOfCode page on the Python wiki.
You should also join the soc2008-general mailing list.
by jtauber : Created on Feb. 27, 2008 : Last modified Feb. 27, 2008 : Categories python summer_of_code : 0 comments (permalink)
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)
by jtauber : Created on Feb. 27, 2008 : Last modified Feb. 27, 2008 : Categories python : 4 comments (permalink)
Evolution of Default Dictionaries in Python
I write a lot of code where I use a dictionary of sets (or lists or counters, etc)
Method 1
dict_set = {}
if key not in dict_set:
dict_set[key] = set()
dict_set[key].add(item)
Method 2
dict_set = {}
dict_set.setdefault(key, set()).add(item)
Method 3
from collections import defaultdict dict_set = defaultdict(set) dict_set[key].add(item)
setdefault was added in Python 2.0 and I've been using (and loving) it for years.
It was only a month or two ago that I discovered collections.defaultdict. Now I use it almost every day.
UPDATE: I forgot to mention that defaultdict was added in Python 2.5. And owing to the fact that int() returns 0 you can use defaultdict(int) for a dictionary of counters.
by jtauber : Created on Feb. 27, 2008 : Last modified Feb. 27, 2008 : Categories python : 10 comments (permalink)