Python 如何为dict中的多个键赋值?

Python 如何为dict中的多个键赋值?,python,dictionary,Python,Dictionary,这就是我打算做的: d = {} d['a']['b'] = 123 我所期待的是这样的一句话: {"a":{"b":123}} 但错误在于: Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'a' 有人能告诉我怎么做我想要的吗?非常感谢 你需要更加明确 d['a'] = { 'b': 123 } 您可能也可以使用defaultdict,将空字典作

这就是我打算做的:

d = {}
d['a']['b'] = 123
我所期待的是这样的一句话:

{"a":{"b":123}}
但错误在于:

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

有人能告诉我怎么做我想要的吗?非常感谢

你需要更加明确

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

您可能也可以使用defaultdict,将空字典作为默认值。

您首先必须创建嵌套字典:

d['a'] = {}
d['a']['b'] = 123
或创建完全格式的嵌套字典:

d['a'] = {'b': 123}
或者使用父词典的,让它根据需要为您创建嵌套词典:

from collections import defaultdict

d = defaultdict(dict)

d['a']['b'] = 123
如果您希望它适用于任意深度,请创建一个自引用工厂函数:

from collections import defaultdict

tree = lambda: defaultdict(tree)

d = tree()

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