Reputation: 11
My code example as below
dict1 = {'c': 2, 'p': 1.0}
Want to alter values of the dict to represent a ratio of itself out of the total values
dict1 = {'c': 0.6666666666666666, 'p': 0.3333333333333333}
Upvotes: 0
Views: 919
Reputation: 5027
>>> d = {'c': 2, 'p': 1.0}
>>> d1 = { k: d[k]/sum(d[k] for k in d) for k in d }
>>> d1
{'c': 0.6666666666666666, 'p': 0.3333333333333333}
>>>
Note: avoid to use dict
as variable name, it's a python's builtin.
Explanation of the one-liner:
d1 = {}
-> d1 is a dictionary
d1 = { k: ... for k in d}
-> all keys of d1
are the ones of d
sum(d[k] for k in d)
-> calculate the sum of all values of d
So, the ...
part above contains d[k]/sum(d[k] for k in d)
: this makes the quotient of the value matching the key k
by the sum of all values of d.
EDIT: as alykhank suggested in comment, it's possible to do this in two lines and save execution time by not recomputing the sum at each iteration.
>>> total = sum(d.values())
>>> d2 = {k: d[k]/total for k in d}
>>> d2
{'c': 0.6666666666666666, 'p': 0.3333333333333333}
>>>
Upvotes: 1