We are given a dictionary and our task is to retrieve a random key-value pair from it. For example, given the dictionary: d = {'aryan': 10, 'harsh': 20, 'kunal': 30} then a possible output could be any one of these: ('aryan', 10), ('harsh', 20), or ('kunal', 30).
Using random.choice()
In this method we first convert the dictionary's key-value pairs into a list of tuples using d.items() and then use random.choice() to select a random pair.
import random
d = {'aryan': 10, 'harsh': 20, 'kunal': 30}
res = random.choice(list(d.items()))
print(res)
Output
('kunal', 30)
Explanation: list(d.items()) is used to convert the dictionary items into a list of tuples and random.choice() randomly selects one element from the list.
Using random.sample()
In this method we use random.sample() to select a single random pair from the dictionary items, this method is similar to random.choice() but works well when you need to sample multiple items.
import random
d = {'aryan': 10, 'harsh': 20, 'kunal': 30}
res = random.sample(list(d.items()), 1)[0]
print(res)
Output
('harsh', 20)
Explanation:
- random.sample() is used to do random sampling from a list and we can even specifying the number of items to sample.
- random.sample() returns a list hence we extract the first element using [0].
Using Iterators and random.randint()
In this method we first create a list of dictionary items using d.items() and then use random.randint() to generate a random index and retrieve the corresponding key-value pair using this index.
import random
d = {'aryan': 10, 'harsh': 20, 'kunal': 30}
items = list(d.items())
res = items[random.randint(0, len(items) - 1)]
print(res)
Output
('harsh', 20)
Explanation: list(d.items()) converts the dictionary into a list of tuples and random.randint(0, len(items) - 1) is used to generate a random index within the range of the list.