Python: Counter - ValueError: too many values to unpack
I recently came across Python’s Counter tool which makes it really easy to count the number of occurrences of items in a list.
In my case I was trying to work out how many times words occurred in a corpus so I had something like the following:
>> from collections import Counter
>> counter = Counter(["word1", "word2", "word3", "word1"])
>> print counter
Counter({'word1': 2, 'word3': 1, 'word2': 1})
I wanted to write a for loop to iterate over the counter and print the (key, value) pairs and started with the following:
>>> for key, value in counter:
... print key, value
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
I’m not sure why I expected this to work but in fact since Counter is a sub class of dict we need to call iteritems to get an iterator of pairs rather than just keys.
The following does the job:
>>> for key, value in counter.iteritems():
... print key, value
...
word1 2
word3 1
word2 1
Hopefully future Mark will remember this!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.