Sometimes, we want to get a random value from dictionary with Python.
In this article, we’ll look at how to get a random value from dictionary with Python.
How to get a random value from dictionary with Python?
To get a random value from dictionary with Python, we can use the random.choice
method with the dictionary’s values
method.
For instance, we write:
import random
d = {'VENEZUELA': 'CARACAS', 'CANADA': 'OTTAWA'}
c = random.choice(list(d.values()))
print(c)
We have the dictionary d
which we want to get a random choice from.
Then we call d.values
to return a generator with the dictionary’s values.
Next we convert to a list with list
.
And then we pick a random choice from the list with random.choice
.
Conclusion
To get a random value from dictionary with Python, we can use the random.choice
method with the dictionary’s values
method.