How to Get Random Keys and Values from a Python Dictionary
This guide explains how to retrieve random keys, values, or key-value pairs (items) from a Python dictionary. We'll cover using the random module's choice(), sample(), and choices() functions, and explain the key differences between them.
Getting a Single Random Key-Value Pair
To get a single, random key-value pair, convert the dictionary's items to a list and use random.choice():
import random
my_dict = {
'name': 'Tom Nolan',
'fruit': 'apple',
'number': 5,
'website': 'tutorialreference.com',
'topic': 'Python'
}
key, value = random.choice(list(my_dict.items())) # Convert to list and choose
print(key, value) # Output: (e.g.,) topic Python
- The
my_dict.items()method will return a view object with all key-value pairs. list(my_dict.items()): Converts the dictionary's items (key-value pairs, which are tuples) into a list of tuples. This is necessary becauserandom.choice()works on sequences, not dictionary views.random.choice(...): Selects a random tuple (key-value pair) from the list.key, value = ...: Unpacks the selected tuple into separatekeyandvaluevariables.
Getting a Single Random Key
To get just a random key:
import random
my_dict = {
'name': 'Tom Nolan',
'fruit': 'apple',
'number': 5,
'website': 'tutorialreference.com',
'topic': 'Python'
}
key = random.choice(list(my_dict)) # Convert keys to a list and choose
print(key) # Output: (e.g.,) topic
list(my_dict): Converts the dictionary to a list of its keys. This is the most concise way to get a list of keys.random.choice(...): Selects a random key from the list.
Getting a Single Random Value
To get a random value:
import random
my_dict = {
'name': 'Tom Nolan',
'fruit': 'apple',
'number': 5,
'website': 'tutorialreference.com',
'topic': 'Python'
}
value = random.choice(list(my_dict.values())) # Convert values to a list
print(value) # Output: (e.g.,) tutorialreference.com
list(my_dict.values()): Creates a list of the dictionary's values.random.choice(...): Selects a random value from the list.
Getting Multiple Random Keys, Values, or Items
Using random.sample() (Unique Elements - Without Replacement)
random.sample() selects a specified number of unique items from a sequence. This is like drawing cards from a deck without putting them back.
import random
my_dict = {
'id': 1,
'name': 'tomnolan',
'age': 30,
'country': 'Italy',
'city': 'Rome',
}
random_keys = random.sample(list(my_dict), 2) # Get 2 random keys
print(random_keys) # Output: (e.g.,) ['age', 'name']
random_values = random.sample(list(my_dict.values()), 2) # 2 random values
print(random_values) # Output: (e.g.,) [30, 'tomnolan']
random_items = random.sample(list(my_dict.items()), 2) # 2 random (key, value) pairs
print(random_items) # Output: (e.g.,) [('country', 'Italy'), ('id', 1)]
random.sample(population, k): Returns a list ofkunique elements chosen frompopulation.- Important:
random.sample()can not return more unique elements than are present in the input. If you ask for more elements than exist, you'll get aValueError.
Using random.choices() (Allows Duplicates - With Replacement)
random.choices() selects elements with replacement, meaning the same item can be chosen multiple times:
import random
my_dict = {
'id': 1,
'name': 'tomnolan',
'age': 30,
'country': 'Italy',
'city': 'Rome',
}
#The k argument specifies how many values to pick.
random_keys = random.choices(list(my_dict), k=2)
print(random_keys) # Output: (e.g.,) ['name', 'country'] (could have duplicates)
random_values = random.choices(list(my_dict.values()), k=2)
print(random_values) # Output: (e.g.,) ['Rome', 30] (could have duplicates)
random_items = random.choices(list(my_dict.items()), k=2)
print(random_items) # Output: (e.g.,) [('id', 1), ('city', 'Rome')] (could have duplicates)
random.choices(population, k=n): Returns a list ofnelements chosen frompopulation, with replacement.