Python multidimensional dictionary
I want to create a multidimensional dictionary in python so that I can access them using the following notation:
test['SYSTEM']['home']['GET']
test['SYSTEM']['home']['POST']
What would be the easiest way to set these values, in other languages ββI can do this:
test['SYSTEM']['home']['GET'] = True
test['SYSTEM']['home']['POST'] = False
+3
source to share
2 answers
You can create a recursive structure collections.defaultdict
like
>>> from collections import defaultdict
>>> nesteddict = lambda: defaultdict(nesteddict)
>>>
>>> test = nesteddict()
>>> test['SYSTEM']['home']['GET'] = True
>>> test['SYSTEM']['home']['POST'] = False
>>>
>>> test['SYSTEM']['home']['GET']
True
>>> test['SYSTEM']['home']['POST']
False
Whenever you access a key in test
that is not in it, it calls the function passed in the argument nesteddict
to create a value for the key.
+5
source to share