简体   繁体   English

嵌套python字典中的增量项目

[英]Increment items in nested python dict

I have a nested Python Dict and I am trying to take values from a list and then iterate them into a Dict's values as such: 我有一个嵌套的Python Dict,并且尝试从列表中获取值,然后将其迭代为Dict的值,如下所示:

for row in rows:
  Dict[A][AA][AAA] += 1

However, when I print my dict, it appears to be adding all of the increments to all of the Dict entries. 但是,当我打印字典时,它似乎是将所有增量添加到所有Dict条目中。 By which I mean that instead of this: 我的意思是代替这个:

{KeyA:{KeyAA:{KeyAAA:5}}}
{KeyB:{KeyBB:{KeyBBB:10}}}

I am getting this: 我得到这个:

{KeyA:{KeyAA:{KeyAAA:15}}}
{KeyB:{KeyBB:{KeyBBB:15}}}

I'm a bit stumped. 我有点难过。

EDIT: This is how the Dicts were created: I first skim through a long table that contains a type classification. 编辑:这是创建字典的方式:我首先浏览包含类型分类的长表。 While I'm doing that, I create a new entry into the main Dict. 在执行此操作时,我在主Dict中创建了一个新条目。 At the same time, I'm collecting all of the unique classifications into a subDict so that I can add this to the main Dict later on: 同时,我将所有唯一分类收集到subDict中,以便稍后可以将其添加到主Dict中:

Dict = {}
subDict = {}
for row in skimRows:
  Dict[row[0]] = {"Type":row[1],"Assoc":{}} # Save each ID and origin Type to Dict
  if item not in subDict: # Check to see if unique item already exists in subDict
    subDict[item] = 0

Here is evidently where I was going wrong. 显然这是我要去的地方。 I was then taking the subDict and plunking this into the main Dict, not realising the inserted subDict was retaining its relationship to the original subDict object: 然后,我将subDict插入到主Dict中,但没有意识到插入的subDict保留了与原始subDict对象的关系:

for key in Dict: # After initial iteration and Type collection, add new subDict to each Dict key
  Dict[key]["Assoc"] = subDict

SOLUTION: Per the correct answer below, I fixed it by adding .copy() 解决方案:根据下面的正确答案,我通过添加.copy()进行了修复。

for key in Dict: # After initial iteration and Type collection, add new subDict to each Dict key
  Dict[key]["Assoc"] = subDict.copy()

Your innermost dictionaries are shared, not unique objects: 您最里面的字典是共享的,而不是唯一的对象:

>>> somedict = {}
>>> somedict['foo'] = {'bar': 0}
>>> somedict['spam'] = somedict['foo']
>>> somedict['foo']['bar'] += 1
>>> somedict['spam']
{'bar': 1}
>>> somedict['foo'] is somedict['spam']
True

The two keys foo and spam both are referring to the same object here, one dictionary object holding a key bar . 此处的两个键foospam都指向同一对象, 一个字典对象包含一个key bar

You should not reuse your dictionaries like this. 您不应该像这样重复使用字典。 Either create a new empty dictiorary: 要么创建一个新的空字典,要么:

somedict['spam'] = {'bar': 0}

or create a (shallow) copy: 或创建(浅)副本:

somedict['spam'] = somedict['foo'].copy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM