如何使用 2 个键和一个值创建 dict?

Joe*_*Joe 1 python dictionary data-structures

在python中,我可以将字典定义为:

d = {}
Run Code Online (Sandbox Code Playgroud)

并将数据存储为:

d['a1'] = 1
Run Code Online (Sandbox Code Playgroud)

如何存储2个密钥?

d['a1']['b1'] = 1
d['a1']['b2'] = 2

d['a2']['b1'] = 3
d['a2']['b2'] = 4
Run Code Online (Sandbox Code Playgroud)

然后打印所有键和值,例如d['a1']

b1 -> 1
b2 -> 2
Run Code Online (Sandbox Code Playgroud)

And*_*ely 5

您可以使用defaultdictfromcollections模块(此处的文档):

from collections import defaultdict

d = defaultdict(dict)

d['a1']['b1'] = 1
d['a1']['b2'] = 2

d['a2']['b1'] = 3
d['a2']['b2'] = 4

print(d['a1'])
Run Code Online (Sandbox Code Playgroud)

印刷:

{'b1': 1, 'b2': 2}
Run Code Online (Sandbox Code Playgroud)