Let’s say I have a dictionary like the following, where values are probability for each key to show up in a text.
dict = {'a':0.66,'b':0.07,'c':0.04 and so on so the values of the dict sum up to one}
say that I want to build another dictionary that has the range of those values has value.
Since we cannot use range() with floats I have tried to first multiply all the values by 100, so they turn into int.
Suppose that we want to substitute those values with their range. So for example ‘a’ will get a range(0,66), ‘b’ range(66,73), ‘c'(73,77) etc.
I have tried to do that with following loop but it doesn’t work:
start = 0
end = 0
for k,v in dict.items():
end+=int(v*100)
range_dict[k]=range(start,end)
start+=end
Can somebody please help me? I am going nuts figuring out what to do!
If you change
to
It should work (using
xrangehere to make it more visible):But if as @Satoru.Logic guessed you want a weighted random number, there are much better ways. Eli Bendersky has a good overview of approaches in Python here.