4

I need to write a counter to a file in order of most occurring to least occurring but I am having a little trouble. When I print the counter it prints in order but when I call counter.items() and then write it to a file it writes them out of order.

I am trying to make it like this:

word      5
word2     4
word3     4
word4     3
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Alex Brashear
  • 864
  • 3
  • 9
  • 15

2 Answers2

13

I'd suggest you to use collections.Counter and then Counter.most_common will do what you're looking for:

Demo:

>>> c = Counter('abcdeabcdabcaba')
>>> c.most_common()
[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]

Write this to a file:

c = Counter('abcdeabcdabcaba')
with open("abc", 'w') as f:
    for k,v in  c.most_common():
        f.write( "{} {}\n".format(k,v) )

help on Counter.most_common:

>>> Counter.most_common?
Docstring:
List the n most common elements and their counts from the most
common to the least.  If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Perhaps mention the [ordereddict](http://docs.python.org/2/library/collections.html#collections.OrderedDict) as well... – Fredrik Pihl May 28 '13 at 20:55
  • Every time I turn around, I spot something handy in `collections` - that and `itertools` don't get nearly enough love IMHO. – Cartroo May 28 '13 at 20:58
2
from operator import itemgetter
print sorted( my_counter.items(),key=itemgetter(1),reverse=True)

should work fine :)

dictionaries have no order which is what a counter is so you must sort the item list if you want it in some order... in this case ordered by the "value" rather than the "key"

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Thanks for the quick response! This prints it out in the desired order which is great, do you know a way to write it to a file though? if I just say print my_counter it prints it out in order but not separated on each line and the real problem is with the writing to a file. Thanks! – Alex Brashear May 28 '13 at 21:03