1

I have a dictionary associating a probability to a char

d = {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd':0.1}

And I am searching a way to associate to each char the lowest value of his frequency distribution. So every char must be associated to the sum of the previous ones. I know dictionary are not ordered but it should return something like

ddist = {'a': 0, 'b': 0.2, 'c': 0.5, 'd': 0.9}

I tried with a loop but I did not find a way to get the previous values...

Any ideas ?

lbeziaud
  • 312
  • 4
  • 13

2 Answers2

3

You can simply iterate over a sorted version of the keys:

d = {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd':0.1}
ddist = {}
t = 0
for key in sorted(d):
    ddist[key] = t
    t += d[key]
Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
1

As dicts are unordered, so you need to define the key order yourself, or use collections.OrderedDict from the start.

>>> def accumulate(seq):
    total = 0
    for item in seq:
        yield total
        total += item
...         
>>> keys = ['a', 'b', 'c', 'd'] #For your dict, this is sorted(d)
>>> dict(zip(keys, accumulate(d[k] for k in keys)))
{'a': 0, 'c': 0.5, 'b': 0.2, 'd': 0.9}
#or
>>> from collections import OrderedDict
>>> OrderedDict(zip(keys, accumulate(d[k] for k in keys)))
OrderedDict([('a', 0), ('b', 0.2), ('c', 0.5), ('d', 0.9)])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504