How do I create a nested dictionary under a key that is yet to exist?
You could use collections.defaultdict
, passing the default factory as dict
:
>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d['key']['subkey'] = 'value'
>>> d
defaultdict(<type 'dict'>, {'key': {'subkey': 'value'}})
To apply further levels of nesting, you can create a defaultdict
that returns defaultdict
s to a n-th depth of nesting, using a function, preferably anonymous, to return the nested default dict(s):
>>> d = defaultdict(lambda: defaultdict(dict))
>>> d['key']['subkey']['subsubkey'] = 'value'
>>> d
defaultdict(<function <lambda> at 0x104082398>, {'key': defaultdict(<type 'dict'>, {'subkey': {'subsubkey': 'value'}})})
Example shows nesting up to depth n=1
You are using a []
list literal not a {}
dict literal:
array['key'] = {}
array['key']['subkey'] = 'value'
But this isn't very useful in a loop.
In a loop you could test if 'key'
is not in array
- which is a cheap operation (O(1)
lookup):
if 'key' not in array:
array['key'] = {}
array['key']['subkey'] = 'value'
But you can use setdefault()
to do the same thing and give key
a default value if it doesn't already have a value, e.g.:
array.setdefault('key', {})['subkey'] = 'value'
And if this looks ugly, then you can always use collection.defaultdict
.