So when I print the Counter (from collections import Counter
) to a file I always get this the literal Counter ({\'Foo\': 12})
Is there anyw
You could change the __str__ method of the counter class by going into the source code for the collections module, but I wouldn't suggest that as that permanently modifies it. Maybe just changing what you print would be more beneficial?
Well this isn't very elegant, but you can simply cast it as a string and cut off the first 8 and last 1 letters:
x = Counter({'Foo': 12})
print str(x)[8:-1]
What about explicitly formatting it into the form that you want?
>>> import collections
>>> data = [1, 2, 3, 3, 2, 1, 1, 1, 10, 0]
>>> c = collections.Counter(data)
>>> '{' + ','.join("'{}':{}".format(k, v) for k, v in c.iteritems()) + '}'
"{'0':1,'1':4,'2':2,'3':2,'10':1}"
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
.