更新字典中的嵌套计数器

时间:2013-09-24 14:28:38

标签: python dictionary counter

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

想象我的CSV:

outerDictKey    CounterKey
apple     purple
apple     blue
pear    purple

基本上我想要:

dictionary = { apple:
                    counter({blue: 1
                     purple: 1})
                pear:
                   counter({purple: 1})
             }

我不知道该怎么做。

myCounter = Counter()
myKey = 'barbara'
counterKey = 'streisand'
largeDict = defaultdict(dict)       
largeDict[myKey] = {myCounter[counterKey] += 1}

直观地看起来它看起来不会起作用,当然它会产生语法错误。

我也试过

largeDict[myKey][myCounter][counterKey]+=1

抛出“TypeError:unhashable type:'Counter'”错误。

最后

>>> largeDict[myKey]=Counter()
>>> largeDict[myKey][myCounter][counterKey]+=1

仍然会出现类型错误。那么如何增加嵌套在字典中的Counter呢?

2 个答案:

答案 0 :(得分:3)

这将有效:

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

largedict[myKey][counterKey]['somethingyouwanttocount']+=1

Counter只是一个带有一些额外功能的词典。但是,作为一个词典,它不能成为词典中的键,也不能成为集合中的条目,这解释了不可避免的异常。

或者,如果您要跟踪有关相干实体的信息,而不是使用嵌套的dicts,则可以将信息(包括计数器)存储在对象中,并将对象放在{{1}中} 有必要的。

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

dict

答案 1 :(得分:1)

如果你只想count occurrences of the strings in a certain column,那就不够了

import collections
data = "Welcome to stack overflow. To give is to get."

print collections.Counter(data.split())

<强>输出

Counter({'to': 2, 'give': 1, 'get.': 1, 'is': 1, 'Welcome': 1, 'To': 1, 'overflow.': 1, 'stack': 1})
相关问题