在python中将字典创建到另一个字典的语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3817529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
syntax for creating a dictionary into another dictionary in python
提问by Compuser7
Possible Duplicate:
syntax to insert one list into another list in python
可能的重复:
在python中将一个列表插入另一个列表的语法
How could be the syntax for creating a dictionary into another dictionary in python
在python中将字典创建到另一个字典的语法如何
回答by Blazer
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
这通常称为将迭代器嵌套到我认为的其他迭代器中
回答by kindall
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
回答by intuited
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
您想将一本字典插入到另一本字典中,作为其元素之一,还是要从另一本字典的键中引用一本字典的值?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
以前的答案已经涵盖了第一种情况,即您在另一个字典中创建一个字典。
To re-reference the values of one dictionary into another, you can use dict.update:
要将一个字典的值重新引用到另一个字典中,您可以使用dict.update:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
对两个字典中都存在的值的更改将在两个字典中都可见:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
这与复制值或用它创建新字典相同,即
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

