RedRaven
RedRaven

Reputation: 735

Why can't I iterate over a Counter in Python?

Why is that when I try to do the below, I get the need more than 1 value to unpack?

for key,value in countstr:
    print key,value


for key,value in countstr:
ValueError: need more than 1 value to unpack

However this works just fine:

for key,value in countstr.most_common():
    print key,value

I don't understand, aren't countstr and countstr.most_common() equivalent?

EDIT: Thanks for the below answers, then I guess what I don't understand is: If countstr is a mapping what is countstr.most_common()? -- I'm really new to Python, sorry if I am missing something simple here.

Upvotes: 2

Views: 5188

Answers (4)

vine_J
vine_J

Reputation: 153

You can't iterate the counter values/keys directly but you can copy them into a list and iterate the list.

s = ["bcdef", "abcdefg", "bcde", "bcdef"]

import collections
counter=collections.Counter(s)

vals = list(counter.values())
keys = list(counter.keys())

vals[0]
keys[0]

Output:

 2
'bcdef'

Upvotes: 0

mgilson
mgilson

Reputation: 309929

No, they aren't equivalent. countstr is a Counter which is a dictionary subclass. Iterating over it yields 1 key at a time. countstr.most_common() is a list which contains 2-tuples (ordered key-value pairs).

Upvotes: 2

suhailvs
suhailvs

Reputation: 21690

A countstr is a Counter which is a subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b'] 

Upvotes: 1

Tim Peters
Tim Peters

Reputation: 70602

No, they're not. Iterating over a mapping (be it a collections.Counter or a dict or ...) iterates only over the mapping's keys.

And there's another difference: iterating over the keys of a Counter delivers them in no defined order. The order returned by most_common() is defined (sorted in reverse order of value).

Upvotes: 6

Related Questions