[英]Values assigned differently in seemingly identical dictionaries
Somehow my two identical nested dictionaries (a dictionary containing dictionaries), created through different means, act differently when I try to assign a new value to a key. 当我尝试为键分配新值时,通过不同方式创建的两个完全相同的嵌套字典(包含字典的字典)以某种方式表现出不同的行为。
d = {'a': {'item': None},'b': {'item': None},'c': {'item': None}}
The first dictionary is created manually, while the second one is created through this code: 第一个字典是手动创建的,而第二个字典是通过以下代码创建的:
data = {"item" : None}
keys = ["a","b","c"]
d2 = dict()
for i in range(len(keys)):
d2[keys[i]] = data
Both of these give seemingly identical dictionaries. 两者都给出了看似相同的字典。
print d
{'a': {'item': None}, 'c': {'item': None}, 'b': {'item': None}}
print d2
{'a': {'item': None}, 'c': {'item': None}, 'b': {'item': None}}
Everything seems good so far, but when I try to change the value of any of the keys, this happens: 到目前为止,一切似乎都不错,但是当我尝试更改任何键的值时,就会发生这种情况:
d["a"]["item"] = "1"
d2["a"]["item"] = "1"
print d
{'a': {'item': '1'}, 'c': {'item': None}, 'b': {'item': None}}
print d2
{'a': {'item': '1'}, 'c': {'item': '1'}, 'b': {'item': '1'}}
I've tried everything I can think of and I can't find anyone that has had a similar problem. 我已经尽力想尽一切办法,但找不到任何遇到类似问题的人。 It just doesn't makes sense, why would it change the value in all three of the inside dictionaries? 只是没有意义,为什么它会更改所有三个内部词典的值? I hope you guys can help. 希望你们能帮上忙。
I'm using Python 2.7.5 我正在使用Python 2.7.5
You need to create a unique dict for each entry, like so: 您需要为每个条目创建一个唯一的字典,如下所示:
keys = ["a","b","c"]
d2 = dict()
for i in range(len(keys)):
d2[keys[i]] = {"item" : None}
Also you might prefer a more pythonic way: 另外,您可能更喜欢使用pythonic方式:
>>> {k:{'item':None} for k in ['a','b','c']}
{'a': {'item': None}, 'c': {'item': None}, 'b': {'item': None}}
When you assign dict2 = dict1
, you are not making a copy of dict1
, it results in dict2
being just another name for dict1
. 当您指定dict2 = dict1
,你是不是做的副本dict1
,它导致dict2
是为另一个名称而已dict1
。
You can do this using deepcopy
: 您可以使用deepcopy
做到这一点:
data = {"item" : None}
keys = ["a","b","c"]
d2 = dict()
for i in range(len(keys)):
d2[keys[i]] = copy.deepcopy(data)
But if you have data like : 但是,如果您有类似这样的数据:
data = {"item1" : None, "item2":{"Book":none}}
another dictionary
inside your data dictionary
, you must have to use deepcopy
like above. 数据dictionary
另一个dictionary
,则必须使用上述的deepcopy
。
Otherwise, there are different way to copy your dict
. 否则,有不同的方法可以复制dict
。 Like 喜欢
d2[keys[i]] = copy.copy(data)
d2[keys[i]] = dict(data)
d2[keys[i]] = data.copy()
You can use any to copy your dict
. 您可以使用any复制您的dict
。 Just use deepcopy
when you have nested dict
嵌套dict
只使用deepcopy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.