简体   繁体   中英

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!

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.

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))
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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM