Divide each python dictionary value by total value

Question:

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!

Asked By: Yang May

||

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.

Answered By: 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))
Answered By: Puneet Mahendra
def div_d(my_dict):

    sum_p = sum(my_dict.values())

    for i in my_dict:
        my_dict[i] = float(my_dict[i]/sum_p)

    return my_dict 

p.s i am totally new to programming but this is the best i could think off.

Answered By: niksy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.