More information about the Underscore mailing list

[_] Python Question

Tim Wintle timwintle at
Fri Dec 18 12:02:24 GMT 2009

On Thu, 2009-12-17 at 23:57 +0000, Matthew Wilkes wrote:
> Anyone else want to play?  Come on Tim, you know you want to.

+1 on defaultdict for newer versions of python 
(assuming len(attributes.keys()) < 1,000,000 or so).

The way I normally write this is:

attributes = {}
for row in mark.fetchall():
   key = row[1]
   vals = attributes.get(key, [])
   attributes[key] = vals

more verbose, but works on 2.4

For python fans:

key = row[1] 

speeds up the two later uses for two reasons:

  (a) There's one less method call on the list object - you're pushing a
new long object onto the stack (1) to do it anyway so the variable
creation time is negligable.

  (b) The hash of the key is stored on immutable types the first time
it's computed - so the dict assignment is relatively quick compared to
the access (the hash function isn't called, it's just an access to a
member of a struct that's probably stored in a register anyway).