为什么更新一个字典对象会影响另一个? [英] Why does updating one dictionary object affect other?

查看:33
本文介绍了为什么更新一个字典对象会影响另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的字典,我们称之为字典 d.这个字典的键是一个整数,每个键的值是另一个字典.我正在 python 2.7 上尝试一个简单的代码来更新一个外键的值,但它似乎正在更新所有外键的值.

希望这些代码能让大家更容易理解.这是我的意见.

<预><代码>>>>模板 = {'mean':0,'median':0}>>>d[0] = 模板>>>d[1] = 模板>>>d[0]['平均值'] = 1>>>d

然后这里是输出:

{0: {'mean':1, 'median':0}, 1:{'mean':1,'median':0}}

你看,我只给 d[0]['mean'] 赋值了 '1',但不知何故 d[1]['mean'] 也被更新了.如果我增加 d 中的键数,它只会更改所有 d 键上的所有 ['mean'] 值.

我在这里做错了什么吗?这是一个错误吗?

解决方案

>>>d[0] = 模板>>>d[1] = 模板

这两个语句使得 d[0]d[1] 指向同一个对象,template.现在您可以使用三个名称访问字典,templated[0]d[1].这样做:

d[0]['mean'] = 1

修改字典对象,可以用上面提到的其他名称引用.

要让它按预期工作,您可以创建 template 对象的副本,如下所示

<预><代码>>>>d[0] = 模板.copy()>>>d[1] = 模板.copy()

现在,d[0]d[1] 指的是两个不同的字典对象.

I have a nested dictionary, let's call it dictionary d. The key of this dictionary is an integer, and the value of each key is another dictionary. I'm trying a simple code on python 2.7 to update the value of one outer key, but it seems that it's updating the values of ALL of the outer key.

Hope these codes will make it easier to understand. Here's my input.

>>> template = {'mean':0,'median':0}
>>> d[0] = template
>>> d[1] = template
>>> d[0]['mean'] = 1
>>> d

and then here's the output:

{0: {'mean':1, 'median':0}, 1:{'mean':1,'median':0}}

you see, I only assigned '1' to d[0]['mean'], but somehow the d[1]['mean'] is also updated. If i increase the number of keys in the d, it will just change ALL of the ['mean'] values on all d keys.

Am I doing anything wrong here? Is this a bug?

解决方案

>>> d[0] = template
>>> d[1] = template

These two statements made both d[0] and d[1] refer to the same object, template. Now you can access the dictionary with three names, template, d[0] and d[1]. So doing:

d[0]['mean'] = 1

modifies a dictionary object, which can be referred with the other names mentioned above.

To get this working as you expected, you can create a copy of the template object, like this

>>> d[0] = template.copy()
>>> d[1] = template.copy()

Now, d[0] and d[1] refer to two different dictionary objects.

这篇关于为什么更新一个字典对象会影响另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆