The output is:
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Can I remove the "Counter" word?
from collections import Counter
word = "hello"
print(Counter(word))
The output is:
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Can I remove the "Counter" word?
from collections import Counter
word = "hello"
print(Counter(word))
To convert a Counter back into a normal dictionary, just do this:
d = dict(Counter(word))
Now it'll look as usual when you print it:
print(d)
It really doesn't make any difference, though. Counter is a dictionary after all. I guess it's ok if you want it to look pretty when printing it.
Of course, you can pass the object to json.dumps. json only sees the dictionary, not the subclass
from collections import Counter
import json
word = "hello"
c = Counter(word)
print(json.dumps(c))
result:
{"l": 2, "o": 1, "h": 1, "e": 1}
that avoids to create a copy as a basic dictionary just to display it properly. More ways to print the contents using just loops on key/values and prints: Formatting output of Counter
Another way is to force basic dict representation method:
print(dict.__repr__(Counter(word)))
result:
{'h': 1, 'o': 1, 'e': 1, 'l': 2}
You can remove the string 'Counter()' with the function strip():
c = Counter('AA')
print(repr(c).strip('Counter()'))
# {'A': 2}
or
print(c.__repr__().strip('Counter()'))
# {'A': 2}
Alternatively you can use string slicing. It should be more efficient (according to @jonrsharpe):
print(c.__repr__()[8:-1]))
# {'A': 2}