【问题标题】:Update Nested Counter in a Dictionary更新字典中的嵌套计数器
【发布时间】:2013-09-24 14:28:38
【问题描述】:

我正在逐行浏览一个大型 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 呢?

【问题讨论】:

  • 所以外层字典直接包含计数器?
  • 当您使用外部字典的键时,我希望它给您一个计数器。增量是指“在计数器中查找字符串并加 1”。所以每次找到“apple”这个词时,它都会在计数器中查找“apple”并添加一个
  • 那为什么不直接使用defaultdict(Counter)呢?你把事情复杂化了。然后你就做largeDict['columnkey']['thing-you-want-count'] += 1

标签: python dictionary counter


【解决方案1】:

这将起作用:

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

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

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

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

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

from collections import defaultdict, Counter
largedict = defaultdict(Counter)
largedict['apple']['purple']+=1

【讨论】:

    【解决方案2】:

    如果你只是想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})
    

    【讨论】:

    • 这里还有更多内容,但为了简单起见,我在帖子中留下了很多内容。我正在使用来自其他列的信息作为键,我需要这样做,否则由于重复,数据将被错误地处理。不过还是谢谢
    • 能否在您的问题中详细解释一下?人们也许能够想出创造性的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2019-12-04
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多