简体   繁体   中英

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!

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM