Divide each python dictionary value by total value

Sum the values, then use a dictionary comprehension to produce a new dictionary with the normalised values:

total = sum(a.itervalues(), 0.0)
a = {k: v / total for k, v in a.iteritems()}

You can squeeze that into a one-liner, but it won’t be as readable:

a = {k: v / total for total in (sum(a.itervalues(), 0.0),) for k, v in a.iteritems()}

I gave sum() with a floating point starting value to prevent the / operator from using floor division in Python 2, which would happen if total and v would both be integers.

In Python 3, drop 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; the value expression is executed for each iteration in the comprehension loop, recalculating the sum() again and again. The sum() loops over all N items in the dictionary, so you end up with a quadratic O(N^2) solution rather than a O(N) solution to your problem.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)