Dong-gyun Kim
Dong-gyun Kim

Reputation: 431

Nested dictionary append element through looping

In general, I created a dictionary with a code like:

dict = {}
if key not in dict:
    dict[key] = [element]
else:
    dict[key].append(element)

But if I want to apply a similar method to the nested dictionary, what should I do? This is something I'm thinking, but of course, it did not work.

dict = {}
if key1, key2 not in dict:
    dict[key][key2] = [element]
else:
    dict[key][key2].append(element)

Upvotes: 0

Views: 75

Answers (1)

DeepSpace
DeepSpace

Reputation: 81604

Use setdefault:

d = {}
d.setdefault('a', {}).setdefault('b', []).append('element')
print(d)
# {'a': {'b': ['element']}}
d.setdefault('a', {}).setdefault('b', []).append('another_element')
# {'a': {'b': ['element', 'another_element']}}

Upvotes: 3

Related Questions