[Python-ideas] Nested dictionaries
Chris Angelico
rosuav at gmail.com
Sat Mar 29 16:46:30 CET 2014
On Sun, Mar 30, 2014 at 2:36 AM, Richard Prosser
<richard.prosser at mail.com> 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'
>
> and once again I wonder why Python does not support that idiom directly, as
> it must be a fairly common requirement. 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.
The NestedDict at the end of that blog post looks like a nice clean
solution; and it's so short that it probably doesn't need to be in the
standard library. But maybe that would make a handy example, if
there's a place in the docs where you'd go looking for that sort of
thing.
Alternatively, you may find it simpler and easier to use a non-nested
dictionary. I store persistent data for my MUD client in a structure
like this:
persist["window/downarr"] = blah blah
Of course, this assumes your keys are simple strings, and it's best
for literals; you can't easily iterate over "everything under
window/", for instance. But if that covers your requirements, it's
probably going to be easier to read and comprehend; and it'd probably
be faster, too, although that shouldn't be a primary consideration.
ChrisA
More information about the Python-ideas
mailing list