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?
Can the below codes be used as a different method?
I have used this alternative way before (edit: although I preferred Moses Koledoye answer):
You are using a
[]
list literal not a{}
dict literal:But this isn't very useful in a loop.
In a loop you could test if
'key'
is not inarray
- which is a cheap operation (O(1)
lookup):But you can use
setdefault()
to do the same thing and givekey
a default value if it doesn't already have a value, e.g.:And if this looks ugly, then you can always use
collection.defaultdict
.You could use a nested
defaultdict
like this, goes arbitrarily deep automatically:(I indented the output for readability.)
Originally saw that from severb.
You could use
collections.defaultdict
, passing the default factory asdict
:To apply further levels of nesting, you can create a
defaultdict
that returnsdefaultdict
s to a n-th depth of nesting, using a function, preferably anonymous, to return the nested default dict(s):Example shows nesting up to depth
n=1