Extending dict (dict's) to allow for multidimensional dictionary

Peter Otten __peter__ at web.de
Sat Mar 5 13:11:17 EST 2011


Ravi wrote:

> I found a solution here:
> 
> http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-
dictionaries-in-python/
> 
> Please tell how good is it?

Follow the link to the cookbook and read Andrew Dalke's comment ;) 
To spell it out:

>>> class D(dict):
...     def __missing__(self, key):
...             result = self[key] = D()
...             return result
...
>>> d = D()
>>> d["a"]["b"]["c"] = 42
>>> d
{'a': {'b': {'c': 42}}}

This is not only simpler, it should also give you faster lookup when the key 
already exists.



More information about the Python-list mailing list