jon_shep jon_shep - 28 days ago 6
Python Question

Can you make Counter not write-out "Counter"?

So when I print the Counter (

from collections import Counter
) to a file I always get this the literal
Counter ({'Foo': 12})


Is there anyway to make the counter not write out so literally? So it would instead write
{'Foo' : 12}
instead of
Counter({'Foo' : 12})
.

Yeah it's picky, but I am sick of grep'n the thing out of my files afterward.

Answer

You could just pass the Counter to dict:

counter = collections.Counter(...)
counter = dict(counter)

In [56]: import collections

In [57]: counter = collections.Counter(['Foo']*12)

In [58]: counter
Out[58]: Counter({'Foo': 12})

In [59]: counter = dict(counter)

In [60]: counter
Out[60]: {'Foo': 12}

I rather like JBernardo's idea better, though:

In [66]: import json

In [67]: counter
Out[67]: Counter({'Foo': 12})

In [68]: json.dumps(counter)
Out[68]: '{"Foo": 12}'

That way, you do not lose counter's special methods, like most_common, and you do not require extra temporary memory while Python builds a dict from a Counter.