Can you make Counter not write-out “Counter”?

后端 未结 4 1755
渐次进展
渐次进展 2021-01-15 13:22

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

4条回答
  •  半阙折子戏
    2021-01-15 13:48

    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.

提交回复
热议问题