如何根据浮点值从字典中随机 select 一个键

How to randomly select a key from a dictionary based on it's float value

假设我有一个字典

{'option one': 5.0, 'option two': 5.0, 'option three': 10.0}

我如何根据上述概率随机 select 一个密钥(即选项一和选项二将有 25% 的被选中。选项 3 将有 50% 的几率被选中)

作为一个班轮:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
picked = random.choices(*zip(*d.items()))[0]
print(picked)
# option one

更多细分:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
# Key-value pairs in dictionary
items = d.items()
# "Transpose" items: from key-value pairs to sequence of keys and sequence of values
values, weights = zip(*items)
# Weighted choice (of one element)
picked = random.choices(values, weights)[0]
print(picked)
# option one

注意 random.choices (which, unlike random.choice,提供 weights 参数)已添加到 Python 3.6。