在python中将字典创建到另一个字典的语法 [英] syntax for creating a dictionary into another dictionary in python
本文介绍了在python中将字典创建到另一个字典的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在python中将一个列表插入另一个列表的语法一个>
如何在python中将字典创建到另一个字典的语法
How could be the syntax for creating a dictionary into another dictionary in python
推荐答案
您可以通过嵌套 {} 容器在字典中声明字典:
You can declare a dictionary inside a dictionary by nesting the {} containers:
d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
然后您可以使用 [] 语法访问元素:
And then you can access the elements using the [] syntax:
print d['dict1'] # {'foo': 1, 'bar': 2}
print d['dict1']['foo'] # 1
print d['dict2']['quux'] # 4
鉴于上述情况,如果您想在字典中添加另一个字典,可以这样做:
Given the above, if you want to add another dictionary to the dictionary, it can be done like so:
d['dict3'] = {'spam': 5, 'ham': 6}
或者如果您更喜欢将项目一一添加到内部字典中:
or if you prefer to add items to the internal dictionary one by one:
d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
这篇关于在python中将字典创建到另一个字典的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文