To get a random value from a dictionary in Python, you can use the random module choice() function, list() function and dictionary values() function.
import random
d = {"a":3, "b": 5, "c":1, "d":2}
print(random.choice(list(d.values())))
#Output:
5
If you want to get a random key from a dictionary, you can use the dictionary keys() function instead.
import random
d = {"a":3, "b": 5, "c":1, "d":2}
print(random.choice(list(d.keys())))
#Output:
d
If you want to get a random key/value pair from a dictionary, you can use the dictionary items() function.
import random
d = {"a":3, "b": 5, "c":1, "d":2}
print(random.choice(list(d.items())))
#Output:
('b',5)
When working with different collections of data, to be able to get a random piece of information from your data can be valuable.
In Python, many times we are working with dictionaries.
We can get a random value from a dictionary easily in Python using the random module choice() function – all we need to do is pass a list of the dictionary values.
To get the dictionary values, we can use the dictionary values() function and convert it to a list using list()
Below shows you an example of how to get a random value from a dictionary variable in Python.
import random
d = {"a":3, "b": 5, "c":1, "d":2}
print(random.choice(list(d.values())))
#Output:
5
Get Random Key from Dictionary Using Python
If you want to get a random key from a dictionary, you can use the dictionary keys() function instead of the values() function.
Below shows you an example of how to get a random key from a dictionary variable in Python.
import random
d = {"a":3, "b": 5, "c":1, "d":2}
print(random.choice(list(d.keys())))
#Output:
d
Get Random Key/Value Pair from Dictionary Using Python
If you want to get a random key/value pair from a dictionary, you can use the dictionary items() function.
Below shows you an example of how to get a random key/value pair from a dictionary variable in Python.
import random
d = {"a":3, "b": 5, "c":1, "d":2}
print(random.choice(list(d.items())))
#Output:
('b',5)
Hopefully this article has been useful for you to learn how to get random values from a dictionary in Python.