在python中创建字典到另一个字典的语法

Com*_*er7 38 python

可能重复:
在python中将一个列表插入另一个列表的语法

怎么可能是在python中创建字典到另一个字典的语法

kin*_*all 101

您可以通过嵌套{}容器在字典中声明字典:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用[]语法访问元素:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4
Run Code Online (Sandbox Code Playgroud)

鉴于上述情况,如果要在字典中添加另一个字典,可以这样做:

d['dict3'] = {'spam': 5, 'ham': 6}
Run Code Online (Sandbox Code Playgroud)

或者如果您希望逐个添加项目到内部字典:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
Run Code Online (Sandbox Code Playgroud)


小智 8

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}
Run Code Online (Sandbox Code Playgroud)

这通常被称为嵌套迭代器我认为是其他迭代器