Python code: Nested dictionary with lambda functions

1 minute read

Published:

Sometimes it is nice to have nested dictionary defined by single line. To avoid initializing keys (e.g. the keys may be unknown before the dictionary is populated) one can use the following code to create a nested dictionary with pre-defined number of levels.

from collections import defaultdict
# three levels deep nested dictionary 
nested_dict = defaultdict( lambda: defaultdict( lambda: defaultdict(dict) ) )

The following test script:

from collections import defaultdict

# function for pretty printintng of nested dictionary
def pretty(d, indent=0):
    # from: https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries
   for key, value in d.items():
      print('\t' * indent + str(key))
      if isinstance(value, dict):
         pretty(value, indent+1)
      else:
         print('\t' * (indent+1) + str(value))

# nested dictionary with predefined number of levels
nested_dict = defaultdict( lambda: defaultdict( lambda: defaultdict(dict) ) )

nested_dict['A']['a'][0] = 'some text'
nested_dict['A']['b'][0] = 'some other text'
nested_dict['B']['a'][1] = 'some text continues'
nested_dict['A']['b'][1] = 'some other text comes here'
nested_dict['C'][0][0]   = 12345

# print "pretty" nested dict
pretty(nested_dict)

yields a easy-to-read representation of the nested dictionary:

A
	a
		0
			some text
	b
		0
			some other text
		1
			some other text comes here
B
	a
		1
			some text continues
C
	0
		0
			12345