Divide each python dictionary value by a common value

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

In any case, can I get a = {'foo': 0.2, 'bar': 0.3, 'baz': 0.5 } on one line? It is necessary to divide each value into a common value ... I just can not do it .. :(

Thank you very much!

+10
python dictionary
source share
4 answers

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.

+20
source share

I did this using 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)) 
0
source share
 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 completely new to programming, but this is the best I could come up with.

0
source share

why the expression does not work without commas a = {k: v / total for total in (sum (a.values ​​()),) for k, v in a.items ()}

0
source share

All Articles