AutoDict - a self initializing dictionary

Eric Freudenthal eric.freudenthal at nyu.edu
Sat Apr 7 06:01:53 EDT 2001


Fellow Pythoneers,

I often find myself creating hierarchical structures of dictionaries.
Initialization of these structures is a nuisance, especially if the values
are not known ahead of time or the depth is not uniform.  I have found the
simple module described below that extends UserDict quite helpful for a
variety of contexts and would like to offer it to others.

First, a simple motivating example, I often need a structure of the form:

score[key1][key2] = value  # please trust that I have reason to not index
with the tuple (key1, key2)

A conventional approach is to build score from a dictionary and a nuisance
helper function, e.g.:

score = {}
def scoreInsert(key1, key2, value):
	if not score.has_key(key1):
		score[key1] = {}
	return score[key1][key2] = value

However, this solution is a mess if the structure has multiple levels or if
the structure is not of uniform depth.

My solution was to generate a class named "AutoDict" that implements a
dictionary whose members are automatically initialized to {}  when they are
accessed by __getitem__().  A function to initialize dictionary entries for
new indices can be specified as a generator function, but I almost always
just use the default

    def __init__(self, generator = lambda key : AutoDict(), name=None,
readOnly = 0):


for example, an AutoDict allows me to conveniently write the following code:

score = AutoDict()
score[1][7] = 8

I'm happy to package this up for the vaults, but don't' want to clog them if
somebody else already has.  I also would appreciate feedback on design
style.  The (tiny) source file is in
http://rlab.cs.nyu.edu/~freudent/xfer/autoDict.py

Regards,
Eric
---
Eric Freudenthal // Courant Institute // New York University
office: 212-998-3345  // cell:917-279-6208
715 Broadway, Room 1011, New York, NY  10003
cell pager: eric.pager at freudenthal.net (100 char limit)






More information about the Python-list mailing list