1

How do you turn probabilities that don't sum up to one into probabilities that sum to one if you don't know the number of keys and the names of the keys? For example:

a = {'g' = 0.1, 'b' = 0.05, 'u' = 0.15, 'i' = 0.2}

To:

a = {'g' = 0.2, 'b' = 0.1, 'u' = 0.3, 'i' = 0.4}
martineau
  • 119,623
  • 25
  • 170
  • 301
jay a
  • 624
  • 2
  • 7
  • 11

2 Answers2

5

What you aim to do is called normalization: you calculate the sum and divide all elements by that sum:

total_inv = 1.0/sum(a.values())
for key,val in a.items():
    a[key] = val*total_inv

Or even shorter (like @Jean-FrançoisFabre says) use dict comprehension:

total_inv = 1.0/sum(a.values())
a = {k:v*total_inv for k,v in a.items()}

but this will construct a new dictionary, so references to the old dictionary are not updated.

In the code we calculate 1.0/sum(..) because a division usually is more expensive than a multiplication and thus can gain some efficiency with that.

Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

Following answers for making dictionaries here, this should solve your problem:

a = {'g':0.1, 'b': 0.05, 'u':0.15, 'i': 0.2}
total = sum(a.values())
new_dict = dict((key, value/total) for (key, value) in a.items())
Community
  • 1
  • 1
p-robot
  • 4,652
  • 2
  • 29
  • 38