Setting a random value from a list in Python [duplicate]

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

  • 4

    First of all that’s not a list, it’s a dictionary.

    – 

  • Does this answer your question? How can I get a random key-value pair from a dictionary?

    – 

  • Yes, so I get this error: TypeError: int() argument must be a string, a bytes-like object or a real number, not ‘tuple’. It seems the values being printed is this: random_ts_id: (‘10271’, 30). How do I get jst the values from the first collum in my list?

    – 




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())).

Leave a Comment