Python | Get random dictionary pair
Sometimes, while working with dictionaries, we can have a situation in which we need to find a random pair from the dictionary. This type of problem can come in games such as lotteries etc. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using random.choice() + list() + items()
The combination of above methods can be used to perform this task. The choice function performs the task of random value selection and list method is used to convert the pairs accessed using items() into a list over which choice function can work. Warning, if the dictionary contains many values, repeatedly converting it to a list may cause performance issues.
Python3
# Python3 code to demonstrate working of# Get random dictionary pair in dictionary# Using random.choice() + list() + items()import random# Initialize dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# Get random dictionary pair in dictionary# Using random.choice() + list() + items()res = key, val = random.choice(list(test_dict.items()))# printing resultprint("The random pair is : " + str(res)) |
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)
Method #2 : Using popitem()
This function is generally used to remove an item from a dictionary and remove it. The logic why this function can be used to perform this task is that the ordering in a dictionary does not depend on the order in which the items were inserted. However, it is important to note that, in newer versions of Python the order will always be the same for the same set of items.
Python3
# Python3 code to demonstrate working of# Get random dictionary pair in dictionary# Using popitem()# Initialize dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# Get random dictionary pair in dictionary# Using popitem()res = test_dict.popitem()# printing resultprint("The random pair is : " + str(res)) |
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)




.png)