Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide each python dictionary value by total value

I have a = {'foo': 2, 'bar': 3, 'baz': 5 }

Is there anyway I can get a = {'foo': 0.2, 'bar': 0.3, 'baz': 0.5 } in one line? Need to divide each value by total value... I just can't get it done.. :(

Thank you so much!

like image 703
Yang May Avatar asked Jun 21 '15 12:06

Yang May


2 Answers

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.

like image 136
Martijn Pieters Avatar answered Oct 05 '22 23:10

Martijn Pieters


I did it using a function

a = {'foo': 2, 'bar': 3, 'baz': 5}   def func1(my_diction):       total = 0       for i in my_diction:           total = total + my_diction[i]       for j in my_diction:           my_diction[j] = (float)(my_diction[j])/total       return my_diction       print (func1(a)) 
like image 24
Puneet Mahendra Avatar answered Oct 05 '22 23:10

Puneet Mahendra