Skip to content Skip to sidebar Skip to footer

How To Write A Counter To A File In Order?

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 coun

Solution 1:

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')
withopen("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 isNone, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]

Solution 2:

from operator import itemgetter
printsorted( 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"

Post a Comment for "How To Write A Counter To A File In Order?"