lundi 22 février 2021

Python: Randomly Select One Key From All Keys in a Dictionary

Let's say I have accessed my dictionary keys using print (hamdict.keys())

Below is a sample output:

enter image description here

I know my dictionary list has a length of 552 elements. I want to randomly select one "key" word from my list and assign it to the variable "starter". I tried to do this with the code below (note: I have a dictionary called hamdict):

random_num = random.randint(0, len(hamdict.keys())-1)
print (random_num)
print (hamdict.keys()[random_num])

I'm able to get a value for random_num so that seems to work. But the second print returns the following error:

enter image description here

How can I fix my code?




Aucun commentaire:

Enregistrer un commentaire