If the type of a Counter object's keys is str
, i.e.:
I could do this:
>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())
>>> vocab_counter = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
'dog\ue000': 1,
'fox\ue000': 1,
'jumps\ue000': 1,
'lazy\ue000': 1,
'over\ue000': 1,
'the\ue000': 2})
What would be a quick and/or pythonic way to add a character to all keys?
Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?
The better way would be adding that character before creating your counter object. You can do it using a generator expression within
Counter
:If it's not possible to modify the words before creating the Counter you can override the
Counter
object in order to add the special character during setting the values for keys.The only other optimised way I can think of is to use a subclass of
Counter
that appends the character when the key is inserted:Demo:
Shortest way i used is,
You could do it with string manipulations: