3

I want to create a multi dimensional 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
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user913059
  • 579
  • 4
  • 19

2 Answers2

5

You can create a recursive collections.defaultdict based structure, like this

>>> 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, which is not there in it, it will invoke the function passed to nesteddict's argument to create a value for the key.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

Instead of using multiple dictionary, you could also use tuples as keys:

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

this might or might not be useful in your case.

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267