关于字典:嵌套python dict中的增量项

Increment items in nested python dict

我有一个嵌套的python dict,我尝试从列表中获取值,然后将其迭代为dict的值,如下所示:

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

但是,当我打印我的dict时,它似乎在向所有dict条目添加所有增量。我指的是,不是这个:

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

我明白了:

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

我有点受不了了。

编辑:这是如何创建听写的:我首先浏览了一个包含类型分类的长表。在执行此操作时,我将在主dict中创建一个新条目。同时,我将所有唯一分类收集到一个子目录中,以便稍后将其添加到主dict中:

1
2
3
4
5
6
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

这显然是我做错的地方。然后,我拿着子目录,把它放到主目录中,没有意识到插入的子目录保留了它与原始子目录对象的关系:

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

解决方案:根据下面的正确答案,我通过添加.copy()修正了它。

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


最里面的词典是共享的,而不是唯一的对象:

1
2
3
4
5
6
7
8
>>> somedict = {}
>>> somedict['foo'] = {'bar': 0}
>>> somedict['spam'] = somedict['foo']
>>> somedict['foo']['bar'] += 1
>>> somedict['spam']
{'bar': 1}
>>> somedict['foo'] is somedict['spam']
True

两个键foospam在这里都指同一个对象,一个字典对象持有一个键bar

你不应该像这样重复使用你的字典。创建新的空词典:

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

或创建(浅)副本:

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