Categories
Python Answers

How to get a random value from dictionary with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *