Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a nested dictionary under a key that is yet to exist?

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?

like image 829
Gray Adams Avatar asked Jul 09 '17 01:07

Gray Adams


1 Answers

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 defaultdicts 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

like image 63
Moses Koledoye Avatar answered Sep 25 '22 08:09

Moses Koledoye