[Python-ideas] Nested dictionaries

Masklinn masklinn at masklinn.net
Sat Mar 29 19:50:29 CET 2014


On 2014-03-29, at 18:29 , Steven D'Aprano <steve at pearwood.info> wrote:
>> I know that there are good
>> solutions like the one at
>> http://ohuiginn.net/mt/2010/07/nested_dictionaries_in_python.html or by
>> using defaultdict but I feel that this really should be part of the
>> language.
> 
> I don't think something like this should be encouraged, and besides it's 
> a four-line solution:
> 
> py> class MyDict(dict):
> ...     def __missing__(self, key):
> ...             t = self[key] = MyDict()
> ...             return t
> ...
> py> x = MyDict()
> py> x[1]['a'][None][True][23.0] = "Surprise!"
> py> x
> {1: {'a': {None: {True: {23.0: 'Surprise!'}}}}}
> 

In most case, a single line probably suffices:

    MyDict = lambda: collections.defaultdict(MyDict)


More information about the Python-ideas mailing list