Summarize the values, then use dictionary understanding to create a new dictionary with normalized values:
total = sum(a.itervalues(), 0.0) a = {k: v / total for k, v in a.iteritems()}
You can compress it into a single line, but it will not be so readable:
a = {k: v / total for total in (sum(a.itervalues(), 0.0),) for k, v in a.iteritems()}
I gave sum() initial floating-point value so that the / operator would not use gender separation in Python 2, which would happen if total and v are integers.
In Python 3, remove the iter* prefixes:
a = {k: v / total for total in (sum(a.values()),) for k, v in a.items()}
Note that you do not want to use {k: v / sum(a.values()) for k, v in a.items()} here; expression expression is performed for each iteration in the understanding loop, recalculating sum() again and again. sum() intersects all N elements in the dictionary, so you get a quadratic solution O (N ^ 2), not an O (N) solution for your problem.
Martijn pieters
source share