[Python-ideas] Nested dictionaries

Steven D'Aprano steve at pearwood.info
Sat Mar 29 18:29:12 CET 2014


On Sat, Mar 29, 2014 at 03:36:06PM +0000, Richard Prosser wrote:
> Not the first time I found myself recently needing to create
> "multi-dimensional" dictionaries, so that I could write something like:
> 
> my_dict = ['a']['b']['b']['a'] = 'fred'

Could you please explain what that is supposed to mean? I can't tell if 
that's supposed to be new syntax, or a typo. Did you mean this instead?

mydict = {'a': {'b': {'b': {}}}}
my_dict['a']['b']['b']['a'] = 'fred'


> and once again I wonder why Python does not support that idiom directly,

It does. There are no special rules to learn, no special syntax to 
memorise, just the same dict syntax as you already know. You create a 
dict with {key: value}, and if the value itself is a dict, you just 
repeat the process with value --> {key: value}, as deeply as you need.

Not every special case needs special syntax.


> as it must be a fairly common requirement.

I doubt it. As the Zen of Python states, "Flat is better than nested". I 
think most people would try to avoid such deeply nested dicts if they 
can. I know I've never needed them.


> 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!'}}}}}


> So, should I propose a PEP?

No. Not every four-line utility class needs to be a built-in.


-- 
Steven


More information about the Python-ideas mailing list