您可以将传递Counter
给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}
不过,我更喜欢JBernardo的想法:
In [66]: import json
In [67]: counter
Out[67]: Counter({'Foo': 12})
In [68]: json.dumps(counter)
Out[68]: '{"Foo": 12}'
这样,您就不会丢失counter
的特殊方法,例如most_common
,并且在Python根据构造字典时不需要额外的临时内存Counter
。