[英]Need help to understand python dictionary
Could someone explain me why the output of this code is same value using a dictionary? 有人可以解释一下为什么使用字典时此代码的输出是相同的值吗? I thought if I add a key to the corresponding variable dictionary I can manipulate it's values.
我以为,如果将键添加到相应的变量字典中,则可以操纵它的值。
Thanks for the help. 谢谢您的帮助。
>>> sample = {}
>>> listDict1 = {}
>>> listDict1['a'] = 'b'
>>> listDict1['c'] = 'd'
>>> sample["item1"] = listDict1
>>> listDict1['a'] = 'x'
>>> listDict1['c'] = 'y'
>>> sample["item2"] = listDict1
>>> sample
{'item2': {'a': 'x', 'c': 'y'}, 'item1': {'a': 'x', 'c': 'y'}}
I expected: 我期望:
{'item2': {'a': 'x', 'c': 'y'}, 'item1': {'a': 'b', 'c': 'd'}}
using the above suggestion comments, i edit the code and works perfectly fine. 使用上面的建议注释,我编辑了代码,并且效果很好。 Thanks.
谢谢。
sample = {} 样本= {}
listDict1 = {}
listDict1['a'] = 'b'
listDict1['c'] = 'd'
sample["item1"] = dict(listDict1)
listDict1['a'] = 'x'
listDict1['c'] = 'y'
sample["item2"] = dict(listDict1)
print id(sample["item1"])
print id(sample["item2"] )
print sample
OUTPUT:
40012512
40012656
{'item2': {'a': 'x', 'c': 'y'}, 'item1': {'a': 'b', 'c': 'd'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.