Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Get random dictionary pair

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 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)

 

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

 
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)

 

Method 3: Using random.sample() and dict.items()

This method is similar to method 1, but uses random.sample() instead of random.choice(). The sample method returns a specified number of random items from a given list or dictionary, while the items() method is used to convert the dictionary into a list of key-value pairs.

Python3




import random
 
# Initialize dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : ", test_dict)
  
# Method 3: Using random.sample()
# Get random dictionary pair in dictionary
# Using random.sample()
res = random.sample(test_dict.items(), 1)
  
# printing result
print("The random pair is : ", res)
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time Complexity: O(k) where k is the number of items in the dictionary.
Auxiliary Space: O(k)
In this method, we use the random.sample() function which is used to return a sample of items from the dictionary. The sample is taken without replacement, meaning that once an item is chosen, it is not chosen again. It takes two parameters as input, the first one is the population from which the sample is to be taken and the second one is the number of items to be chosen. In this case, we pass the items() function of the dictionary as the population and 1 as the number of items to be chosen. This returns a list of tuples, each tuple containing one randomly chosen key-value pair from the dictionary.

METHOD 4:Using hashlib

APPROACH:

This Python code generates a random key-value pair from a given dictionary, without using the random module. It does this by first getting the md5 hash of the dictionary as a string, and then converting this hash string to a random integer between 0 and 2^128 – 1. It then uses this random integer to get a random key-value pair from the dictionary.

ALGORITHM:

1. Define the input dictionary dict1.
2.Get the md5 hash of the dictionary as a string using hashlib.md5(str(dict1).encode(‘utf-8’)).hexdigest().
3. Convert the hash string to an integer using int(hash_str, 16).
4. Get a random key from the dictionary by taking the hash integer modulo the length of the dictionary (hash_int % len(dict1)) and using list(dict1.keys())[…] to get the key at that index.
5. Use the random key to retrieve its corresponding value from the dictionary (dict1[random_key]).
6. Print the original dictionary and the random key-value pair.

Python3




import hashlib
 
# define the dictionary
dict1 = {'Gfg': 1, 'best': 3, 'is': 2}
 
# get the md5 hash of the dictionary as a string
hash_str = hashlib.md5(str(dict1).encode('utf-8')).hexdigest()
 
# convert the hash string to an integer
hash_int = int(hash_str, 16)
 
# get the key-value pair based on the hash integer
random_key = list(dict1.keys())[hash_int % len(dict1)]
random_value = dict1[random_key]
 
print("The original dictionary is:", dict1)
print("The random pair is:", (random_key, random_value))


Output

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

Time complexity: The time complexity of this code is O(1), since the md5 hash function and integer conversion take constant time, and the dictionary lookup by key takes constant time on average.

Space complexity: The space complexity of this code is also O(1), since the only additional memory used is for the hash string and hash integer, which have constant size regardless of the size of the input dictionary.

RELATED ARTICLES

Most Popular

Recent Comments