Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a nested dictionary of arbitrary depth in Python

I would like to create a dictionary where I can assign a value several layers deep inside the nested dictionary without explicitly creating the outer layers first. Here's what I'd like to be able to do:

d = {} # or whatever Python object works
d['a']['b']['c'] = 3

Here's what I've tried so far:

If I have a normal dictionary, I can assign a key like so:

d = {}
d['a'] = 1

but not like so:

d['a']['b'] = 2

However, I can use a defaultdict to do that like so:

from collections import defaultdict
dd = defaultdict(dict)
dd['a']['b'] = 2

However, I still can't do a deeply nested dictionary

from collections import defaultdict
dd = defaultdict(dict)
dd['a']['b']['c'] = 3

I know I could do this with a recursive function but I was hoping there would be a simple way to do this. Is there?

EDIT:

I also tried this but it didn't work:

from collections import defaultdict
dd = defaultdict(defaultdict)
dd['a']['b']['c'] = 3
like image 512
jss367 Avatar asked Aug 14 '26 15:08

jss367


1 Answers

You can use this, as a reference.

from collections import defaultdict
import json
def recursive_dict():
    return defaultdict(recursive_dict)

x = recursive_dict()
x['a']['b']['c']=3
print(json.dumps(x))

Output:

{"a": {"b": {"c": 3}}}