You need to sum the values, then divide each count by the sum:
total = sum(x.values(), 0.0)
for key in x:
x[key] /= total
By starting the sum with 0.0
we make sure total
is a floating point value, avoiding the Python 2 floor division behaviour of /
with integer operands.
Demo:
>>> from collections import Counter
>>> x = Counter(['abc','abc','def','jkl'])
>>> total = sum(x.values(), 0.0)
>>> for key in x:
... x[key] /= total
...
>>> x
Counter({'abc': 0.5, 'jkl': 0.25, 'def': 0.25})
>>> y = Counter(['abc','def','def','pqr', 'pr', 'foo', 'bar'])
>>> total = sum(y.values(), 0.0)
>>> for key in y:
... y[key] /= total
...
>>> y
Counter({'def': 0.2857142857142857, 'pr': 0.14285714285714285, 'abc': 0.14285714285714285, 'bar': 0.14285714285714285, 'pqr': 0.14285714285714285, 'foo': 0.14285714285714285})
If you need to sum the counters, you'd need to re-normalize the resulting counter separately; summing two normalized counters means you have a new counter whole values sum to 2, for example.