Search code examples
pythondictionaryrandomprobability

Choose dictionary key randomly based on value


I have a dictionary that looks like this: {"one": 5, "two": 1, "three": 25, "four": 14}

I want to choose a key from the dictionary in proportion to the values, i.e. "three" would have the highest chance, then "four" then "one" and then "two". I've looked at this question however it seems to be specific to when the numbers add up to 1.

I've really no idea how to start, help would be appreciated.


Solution

  • Use random.choices with the weights parameter:

    random.choices(population, weights=None, *, cum_weights=None, k=1)

    Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

    If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights

    import random
    
    d = {"one": 5, "two": 1, "three": 25, "four": 14}
    keys = list(d.keys())
    values = list(d.values())
    random_key = random.choices(keys, weights=values)
    
    print(random_key)
    # ['three']