Expandable 2D Dictionaries?

Carsten Haese carsten at uniqsys.com
Fri Jul 6 18:05:42 CEST 2007


On Fri, 2007-07-06 at 15:43 +0000, Robert Dailey wrote:
> Hi,
> 
> I am interested in creating an expandable (dynamic) 2D dictionary. For
> example:
> 
> myvar["cat"]["paw"] = "Some String"
> 
> The above example assumes "myvar" is declared. In order for this to
> work, I have to know ahead of time the contents of the dictionary. For
> the above to work, my declaration must look like:
> 
> myvar = {"cat": {"paw":""} }
> 
> I would like to not have to declare my dictionary like this, as it
> does not allow it to be expandable. I'm very new to Python (I'm a
> professional C++ programmer. Any comparisons to C++ would help me
> understand concepts).
> 
> Is there a way that when I index into my dictionary using an "unknown"
> index (string), that python will dynamically add that key/value pair?

Sounds like a job for Python2.5's defaultdict:

from collections import defaultdict
class magicdict(defaultdict):
   def __init__(self):
      self.default_factory = magicdict

myvar = magicdict()
myvar["cat"]["paw"] = "Some String"

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list