Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 392
RedRaven Avatar asked Feb 13 '26 23:02

RedRaven


1 Answers

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).

like image 154
Tim Peters Avatar answered Feb 16 '26 12:02

Tim Peters