I have an empty array.
I want to assign a value like this: array[key][subkey] = 'value'
This produces a KeyError as array[key] does not exist yet.
What do I do? I tried the following...
array['key'] = None
array['key']['subkey'] = 'value'
TypeError: 'NoneType' object does not support item assignment
I tried:
array['key'] = []
array['key']['subkey'] = 'value'
TypeError: list indices must be integers, not str
I tried:
array['key'] = ['subkey']
array['key']['subkey'] = 'value'
TypeError: list indices must be integers, not str
So what do I do?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With