Search code examples
pythonpython-3.xdictionarydefaultdict

Python3.6 4-level dictionaries giving KeyError


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?


Solution

  • 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.