How to randomly select an item from a Python dictionary?

Published on Aug. 22, 2023, 12:17 p.m.

To randomly select an item from a Python dictionary, you can use the random.choice() function with the dictionary’s items() method to select a random key-value pair, and then access either the key, the value, or both as needed. Here is an example:

import random

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
random_key, random_value = random.choice(list(my_dict.items()))

print("Random key:", random_key)
print("Random value:", random_value)

In this example, random.choice() is used with list(my_dict.items()) to select a random key-value pair from the dictionary. The resulting pair is assigned to random_key and random_value, which can then be printed or used in further computations.

Note that the list() call is necessary because my_dict.items() returns a dictionary view object in Python 3, which cannot be directly used with random.choice(). By converting the view to a list, we create a sequence that random.choice() can work with.

Also note that the approach above assumes that you want to select a random key-value pair from the dictionary with equal probability. If you only want to select a random key or a random value, you can modify the code to use either dict.keys() or dict.values() instead of dict.items() and extract the desired element from the resulting tuple.

Tags: