Python-更新一本字典中的值将更新所有字典中的值 [英] Python - Updating value in one dictionary is updating value in all dictionaries
问题描述
我有一个名为lod
的词典列表.所有词典具有相同的键,但值不同.我正在尝试为所有词典中的同一键更新值列表中的一个特定值.
I have a list of dictionaries called lod
. All dictionaries have the same keys but different values. I am trying to update one specific value in the list of values for the same key in all the dictionaries.
我正在尝试通过以下for循环来实现:
I am attempting to do it with the following for loop:
for i in range(len(lod)):
a=lod[i][key][:]
a[p]=a[p]+lov[i]
lod[i][key]=a
发生的事情是每个字典正在更新len(lod)
次,因此应该在lod[0][key][p]
上添加lov[0]
,但是要在其中添加lov[0]+lov[1]+....
.
What's happening is each is each dictionary is getting updated len(lod)
times so lod[0][key][p]
is supposed to have lov[0]
added to it but instead it is getting lov[0]+lov[1]+....
added to it.
我在做什么错了?
这是我声明字典列表的方式:
Here is how I declared the list of dicts:
lod = [{} for _ in range(len(dataul))]
for j in range(len(dataul)):
for i in datakl:
rrdict[str.split(i,',')[0]]=list(str.split(i,',')[1:len(str.split(i,','))])
lod[j]=rrdict
推荐答案
问题出在如何创建词典列表.您可能做了这样的事情:
The problem is in how you created the list of dictionaries. You probably did something like this:
list_of_dicts = [{}] * 20
实际上是相同 dict
20次.尝试做这样的事情:
That's actually the same dict
20 times. Try doing something like this:
list_of_dicts = [{} for _ in range(20)]
没有看到您是如何实际创建的,这只是一个示例问题的示例解决方案.
Without seeing how you actually created it, this is only an example solution to an example problem.
要确定,请打印以下内容:
To know for sure, print this:
[id(x) for x in list_of_dicts]
如果在* 20
方法中定义了它,则每个dict
的id
是相同的.在列表理解方法中,id
是唯一的.
If you defined it in the * 20
method, the id
is the same for each dict
. In the list comprehension method, the id
is unique.
这篇关于Python-更新一本字典中的值将更新所有字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!