Python
Dictionary
Key-Value Pair
Random Selection
Programming Tips

How can I get a random key-value pair from a dictionary?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Python, dictionaries are optimized for key lookup, not random indexing. That means there is no direct built-in method to ask a dictionary for "one random item," so the usual solution is to pick from a temporary list or pick a random key and then retrieve its value.

The Simplest Correct Approach

For ordinary code, convert the dictionary items to a list and use random.choice.

python
1import random
2
3data = {
4    "apple": 3,
5    "banana": 5,
6    "orange": 2,
7}
8
9key, value = random.choice(list(data.items()))
10print(key, value)

This is clear and correct. Each key-value pair has equal probability because list(data.items()) produces one entry per dictionary item.

Picking a Random Key First

If you only want a random item and do not mind two steps, you can choose a random key and then index back into the dictionary.

python
1import random
2
3data = {
4    "apple": 3,
5    "banana": 5,
6    "orange": 2,
7}
8
9key = random.choice(list(data))
10value = data[key]
11print(key, value)

This is functionally equivalent for normal dictionaries because iterating a dictionary yields keys.

Handling Large Dictionaries

The downside of both common patterns is that they build a temporary list. For a small or medium dictionary, that cost is negligible. For a very large dictionary, repeated random selection can become expensive because you keep materializing the keys or items.

If you need many random selections, consider caching the keys or items once and keeping them in sync with the dictionary.

python
1import random
2
3data = {
4    "apple": 3,
5    "banana": 5,
6    "orange": 2,
7}
8
9cached_items = list(data.items())
10
11for _ in range(3):
12    print(random.choice(cached_items))

This is especially useful when the dictionary is mostly read-only and the selection happens often.

What About random.sample?

random.sample also works if you want one or more random keys, but for a single choice it is less direct than random.choice.

python
1import random
2
3data = {
4    "apple": 3,
5    "banana": 5,
6    "orange": 2,
7}
8
9key = random.sample(list(data.keys()), 1)[0]
10print(key, data[key])

Use sample when the real problem is "pick several distinct keys" rather than "pick one random pair."

Empty Dictionaries Need a Guard

An empty dictionary has no random item to choose. Both random.choice and random.sample will raise an exception if you pass an empty sequence.

python
1import random
2
3def random_item(mapping):
4    if not mapping:
5        raise ValueError("dictionary is empty")
6    return random.choice(list(mapping.items()))

Guarding explicitly makes the failure mode clearer to callers.

If You Need Cryptographic Randomness

The random module is fine for simulations, shuffling, games, and ordinary application logic. It is not intended for security-sensitive selection.

If the choice affects tokens, secrets, or security decisions, use secrets.choice instead:

python
1import secrets
2
3data = {
4    "apple": 3,
5    "banana": 5,
6    "orange": 2,
7}
8
9key, value = secrets.choice(list(data.items()))
10print(key, value)

The surrounding pattern stays the same; only the randomness source changes.

Why There Is No dict.random_item()

Python dictionaries preserve insertion order, but they are still hash tables under the hood, not array-like containers with cheap random indexing. Adding a built-in random item operation would not avoid the basic issue that keys are not stored as a simple indexable list for API purposes.

That is why explicit conversion is the idiomatic approach.

Common Pitfalls

The most common mistake is trying random.choice(data) directly. A dictionary is iterable, but it is not a sequence, so choice cannot index it the way it can index a list.

Another mistake is rebuilding list(data.items()) inside a hot loop when the dictionary rarely changes. Cache the list if you need repeated random picks.

Developers also forget to handle the empty-dictionary case, which leads to an unhelpful exception from deeper inside the random module.

Finally, be clear about whether you need a random key, a random value, or a random key-value pair. Those are related but slightly different tasks.

Summary

  • The simplest solution is random.choice(list(my_dict.items())).
  • You can also pick a random key and then read the corresponding value.
  • For repeated selection, cache keys or items instead of rebuilding lists every time.
  • Guard against empty dictionaries before choosing.
  • Use secrets.choice instead of random.choice for security-sensitive selection.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.