Skip to content

Instantly share code, notes, and snippets.

@yamatt
Created October 18, 2011 14:13
Show Gist options
  • Save yamatt/1295517 to your computer and use it in GitHub Desktop.
Save yamatt/1295517 to your computer and use it in GitHub Desktop.
select random key that is weighted by it's value
from random import choice
d = {
'foo1': 1,
'foo2': 5,
'foo3': 3
}
choice([k for k in d for x in range(d[k])])
## think of it as
L = []
for k in d:
for x in range(d[k]):
L.append(k)
choice (L)
# L ends up end up as this list:
['foo1', 'foo2', 'foo2', 'foo2', 'foo2', 'foo2', 'foo3', 'foo3', 'foo3']
"""
By using choice you obviously have the most chance of it selecting 'foo2' in the region of 5 in 9 chance.
Memory usage is high for higher numbers so don't use this method for lots of choices or more precise chances of probability.
It will also only work with integers.
"""
@yamatt
Copy link
Author

yamatt commented Oct 18, 2011

By using choice you obviously have the most chance of it selecting 'foo2' in the region of 5 in 9 chance.
Memory usage is high for higher numbers so don't use this method for lots of choices or more precise chances of probability.
It will also only work with integers.

@yamatt
Copy link
Author

yamatt commented Oct 19, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment