Judking
Judking

Reputation: 6381

How to assign value to multiple keys in dict?

This is what I intend to do:

d = {}
d['a']['b'] = 123

What I expect is a dict like this:

{"a":{"b":123}}

But the error is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'

Could anyone tell me how to do exactly what I want? Thanks a lot!

Upvotes: 0

Views: 318

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125068

You'll first have to create the a nested dictionary:

d['a'] = {}
d['a']['b'] = 123

or create the nested dictionary fully formed:

d['a'] = {'b': 123}

or use a collections.defaultdict() object for the parent dictionary to have it create nested dictionaries for you on demand:

from collections import defaultdict

d = defaultdict(dict)

d['a']['b'] = 123

If you expect this to work for any arbitrary depth, create a self-referential factory function:

from collections import defaultdict

tree = lambda: defaultdict(tree)

d = tree()

d['a']['b'] = 123
d['foo']['bar']['baz'] = 'spam'

Upvotes: 7

unwind
unwind

Reputation: 400139

You need to be more explicit.

d['a'] = { 'b': 123 }

You could probably use a defaultdict too, with an empty dictionary as the default value.

Upvotes: 4

Related Questions