jss367
jss367

Reputation: 5381

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

Upvotes: 2

Views: 909

Answers (2)

Tuan Le PN
Tuan Le PN

Reputation: 384

It seems that you want to use a list of items as a dictionary's key. Why don't you try with tuple? Cannot use a list as a dictionary's key.

d = dict()
d[('a')] = 1
print(d[('a')])
d[('a')] = 11
print(d[('a')])

d[('a', 'b')] = 2
print(d[('a', 'b')])
d[('a', 'b')] = 21
print(d[('a', 'b')])

d[('a', 'b', 'c')] = 3
print(d[('a', 'b', 'c')])
d[('a', 'b', 'c')] = 31
print(d[('a', 'b', 'c')])

d[('a', 'b', 'd')] = 32
print(d[('a', 'b', 'd')])

Upvotes: 1

user15801675
user15801675

Reputation:

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}}}

Upvotes: 6

Related Questions