Skip to content
Related Articles

Related Articles

Python | Get random dictionary pair

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Jun, 2021

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 dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("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 result
print("The random pair is : " + str(res))

Output : 

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 dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Get random dictionary pair in dictionary
# Using popitem()
res = test_dict.popitem()
 
# printing result
print("The random pair is : " + str(res))

Output : 

The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!