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


Instead of using multiple dictionaries, you can also use tuples as keys:

my_dict = {}
my_dict[('SYSTEM', 'home', 'GET')] = True

      



it may or may not be helpful in your case.

+1


source







All Articles