Monday, June 11, 2007

Standard Gems: collections

This until-recently-lonely module only houses two alternative collection types, deque and defaultdict, but promises useful things today and more to come. Anytime we have a good place to put things, we find more things to put there. With the new defaultdict type, collections is finally more than just that thing you use to get a deque: its a full fledged utility library. More optimized collection types (chains, B-Trees, and bags, anyone?) are sure to come, so keep your eye here every new Python release changelog, and maybe you'll get an early Christmas present.

Here is a quick rundown of what is offered today, using possibly silly examples.

d = deque()
d.extend(xrange(10))
while d:
print d.popleft()

What you see here is that deque acts like a list but has mirror versions of many end-modifying operations, like append, extend, and pop, which operate on the 'left' side. A list is far less efficient with insertion and popping from anywhere but the end of the list. This makes deque great for First-In-First-Out structures, where a list is more suited for a First-In-Last-Out setup.

dd = collections.defaultdict(lambda: None)
dd['a'] = 1
dd['b'] = 2
print dd['c'] or 3

Here we automatically handle a non-existant key with a default value, None. A factory callable is used, so that we can actually return different values, but we don't get the key. One interesting use is itertools.count().next as the factory, which means every missing key is automatically filled with an automatically incrementing integer.

2 comments:

Kent said...

For me the most common uses of defaultdict are cases where I need to accumulate a count or a list. For example a word count:

d=defaultdict(int)
for word in words:
  d[word] += 1

or to accumulate a list of first names corresponding to last names:

d=defaultdict(list)
for first, last in names:
  d[last].append(first)

Jorge said...

With the queue I have always had the feeling that is a Thread-related queue and not a normal datastructure, does it has some kind of performance issue? I prefer to use [].append [].remove(0) which for some reason is faster then [].insert(0) [].pop()


As for the dict.

I like to use is as follows for groups of data that are optional. self.items=collections.defaultdict(str)

I have this nice usecase in which I got a set of messages that represent a flow, with some optional. The above just lets me set non-existant message to ''.

You need a bigger trick to make the default something like MISSING, you will have to do as follows

self.items=collections.defaultdict(lambda : "MISSING")

which is a bit ugly but it works nice.

I write here about programming, how to program better, things I think are neat and are related to programming. I might write other things at my personal website.

I am happily employed by the excellent Caktus Group, located in beautiful and friendly Carrboro, NC, where I work with Python, Django, and Javascript.

Blog Archive