pythonlocust

Setting a random value from a list in Python


Basic question, but how do I pick random values from this list:

TS_IDs = {
'69397': 30,
'10259': 30,
'87104': 30
}

Using this function:

def set_ts_id_random():
ts_id_random = <here I want to pick a random value>
print("random_ts_id:", ts_id_random)
return ts_id_random

Solution

  • Use random.choice to choose a value from the dictionary's value:

    import random
    
    TS_IDs = {
    '69397': 30,
    '10259': 30,
    '87104': 30
    }
    
    def set_ts_id_random():
        ts_id_random = random.choice(list(TS_IDs.values()))
        print("random_ts_id:", ts_id_random)
        return ts_id_random
    
    set_ts_id_random()
    

    Output:

    random_ts_id: 30
    

    Remember, TS_IDs is a dict, not a list. It consist of key/value pairs. My code returns a random value, but if you'd rather have a random key, change ts_id_random = random.choice(list(TS_IDs.values())) to ts_id_random = random.choice(list(TS_IDs.keys())).