Menu Close

How to get a random value from dictionary with Python?

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.

For instance, we write

import random

d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
c = random.choice(list(d.values()))

to call random_choice with the list of dict values that we get from dict d with list(d.values()) to return a random dict value from d.

Conclusion

To get a random value from dictionary with Python, we can use the random.choice method.

Posted in Python, Python Answers