[Tutor] Careful Dictionary Building

Paul McGuire ptmcg at austin.rr.com
Sat Dec 29 22:15:27 CET 2007


1. Don't name your dict 'dict' or your list 'list', as this then masks the
builtin dict and list types.
2. Your application is a textbook case for defaultdict:
    
from collections import defaultdict

recordDict = defaultdict(list)
for record in recordList:
    recordDict[record[0]].append(record)

Voila!  No key checking, no keeping of separate key lists (wrong for many
other reasons, too), just let defaultdict do the work.  If the key does not
exist, then defaultdict will use the factory method specified in its
constructor (in this case, list) to initialize a new entry, and then the new
record is appended to the empty list.  If the key does exist, then you
retreive the list that's been built so far, and then the new record gets
appended.

-- Paul



More information about the Tutor mailing list