0

I want to deal with a nested dictionary in python for purpose of storing unique data. However, I don't know what the right way to do it. I tried the following:

my_dict = collections.defaultdict(dict)
my_dict[id1][id2][id2][id4] = value

but it causes KeyError. What is the right way to do so?

smci
  • 32,567
  • 20
  • 113
  • 146
chetra tep
  • 189
  • 5
  • 20

2 Answers2

2

If you want to create a nested defaultdict to as many depths as you want then you want to set the default type of the defaultdict to a function that returns a defaultdict with the same type. So it looks a bit recursive.

from collections import defaultdict

def nest_defaultdict():
    return defaultdict(nest_defaultdict)

d = defaultdict(nest_defaultdict)
d[1][2][3] = 'some value'
print(d)
print(d[1][2][3])

# Or with lambda
f = lambda: defaultdict(f)
d = defaultdict(f)

If you don't require any arbitrary depth then Fuji Clado's answer demonstrates setting up the nested dict and accessing it.

Steven Summers
  • 5,079
  • 2
  • 20
  • 31
1

One Simple Approach

mainDict = {}
mainDict['id1']={}
mainDict['id1']['id2'] ={}
mainDict['id1']['id2']['id3'] = 'actualVal'

print(mainDict)


# short explanation of defaultdict

import collections

# when a add some key to the mainDict, mainDict will assgin 
# an empty dictionary as the value

mainDict = collections.defaultdict(dict)

# adding only key, The value will be auto assign.
mainDict['key1']

print(mainDict)
# defaultdict(<class 'dict'>, {'key1': {}})

# here adding the key 'key2' but we are assining value of 2
mainDict['key2'] = 2 
print(mainDict)

#defaultdict(<class 'dict'>, {'key1': {}, 'key2': 2})


# here we are adding a key 'key3' into the mainDict
# mainDict will assign an empty dict as the value.
# we are adding the key 'inner_key' into that empty dictionary
# and the value as 10

mainDict['key3']['inner_key'] = 10
print(mainDict)

#defaultdict(<class 'dict'>, {'key1': {}, 'key2': 2, 'key3': {'inner_key': 10}})
Fuji Komalan
  • 1,979
  • 16
  • 25