Advanced Dictionary

Peter Otten __peter__ at web.de
Wed Jun 16 09:10:18 EDT 2010


Thomas Lehmann wrote:

>> class AutoValueDict(dict):
>>     def __makeitem__(self, key):
>>         return self.setdefault(key, {})

I think it's bad style to invent your own __whatever__() methods, I'd rather 
call them _whatever().

>>     def __getitem__(self, key):
>>         return self.get(key, self.__makeitem__(key))
>>
>> I would like to have a dictionary which ensures dictionaries as values
>> except when I'm assigning another:
>>
>> dict["abc"]["xyz"]["123"]["456"] = 123
>>
>> How can I do this without many "if" and "else"?
>>
> 
> Oh no... of course like this:
>     return self.setdefault(key, AutoValueDict())
> 

An alternative implementation (requires Python 2.5):

>>> class A(dict):
...     def __missing__(self, key):
...             print "creating subdict for", key
...             value = A()
...             self[key] = value
...             return value
...
>>> a = A()
>>> a["x"]["y"]["z"] = 42
creating subdict for x
creating subdict for y
>>> a
{'x': {'y': {'z': 42}}}

Peter



More information about the Python-list mailing list