更新字典中的嵌套计数器

von*_*ses 2 python counter dictionary

我正在逐行浏览一个大型 CSV 文件。我想要做的是计算特定列中字符串的出现次数。我遇到麻烦的是,我希望将计数器嵌套在字典中,其中外部字典的键是另一列的值。我需要这样做,否则数据将被错误处理,因为存在重复项。

想象一下我的 CSV:

outerDictKey    CounterKey
apple     purple
apple     blue
pear    purple
Run Code Online (Sandbox Code Playgroud)

所以基本上我想要:

dictionary = { apple:
                    counter({blue: 1
                     purple: 1})
                pear:
                   counter({purple: 1})
             }
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做。

myCounter = Counter()
myKey = 'barbara'
counterKey = 'streisand'
largeDict = defaultdict(dict)       
largeDict[myKey] = {myCounter[counterKey] += 1}
Run Code Online (Sandbox Code Playgroud)

直观上这看起来不起作用,当然它会给出语法错误。

我也尝试过

largeDict[myKey][myCounter][counterKey]+=1
Run Code Online (Sandbox Code Playgroud)

这会引发“TypeError: unhashable type: 'Counter'”错误。

最后

>>> largeDict[myKey]=Counter()
>>> largeDict[myKey][myCounter][counterKey]+=1
Run Code Online (Sandbox Code Playgroud)

这仍然给出类型错误。那么如何增加嵌套在字典中的计数器呢?

Mar*_*cin 7

这将起作用:

myCounter = Counter()
largedict = { myKey:
                    {counterKey: myCounter
                     anotherKey: Value2}
             }

largedict[myKey][counterKey]['somethingyouwanttocount']+=1
Run Code Online (Sandbox Code Playgroud)

Counter只是一个具有一些额外功能的字典。然而,作为一个字典,它不能是字典中的键,也不能是集合中的条目,这解释了不可散列的异常。

或者,如果您要跟踪有关连贯实体的信息,而不是使用嵌套dicts,您可以将信息(包括计数器)存储在对象中,并dict根据需要将对象放入 a 中。

如果每个值都是一个计数器,那么只需使用defaultdict:

from collections import defaultdict, Counter
largedict = defaultdict(Counter)
largedict['apple']['purple']+=1
Run Code Online (Sandbox Code Playgroud)