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