# How to Get a Random Entry from a Python Dictionary

## Problem Formulation and Solution Overview

This article will show you how to get a random entry from a Dictionary in Python.

To make it more interesting, we have the following running scenario:

π¨βπ« The Plot: Mr. Sinclair, an 8th great Science Teacher, is giving his students a quiz on the first 25 Periodic Table elements. He has asked you to write a Python script so that when run, it generates a random key, value, or key:value pair from the Dictionary shown below to ask his students.

```els = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li',
'Beryllium': 'Be', 'Boron': 'B', 'Carbon': 'C',
'Nitrogen': 'N', 'Oxygen': 'O', 'Fluorine': 'F',
'Neon': 'Ne', 'Sodium': 'Na', 'Magnesium': 'Mg',
'Aluminum': 'Al', 'Silicon': 'Si', 'Phosphorus': 'P',
'Sulfur': 'S', 'Chlorine': 'Cl', 'Argon': 'Ar',
'Potassium': 'K', 'Calcium': 'Ca', 'Scandium': 'Sc',
'Titanium': 'Ti', 'Vanadium': 'V', 'Chromium': 'Cr',
'Manganese': 'Mn'}```

π¬ Question: How would we write code to get a random entry from a Dictionary?

We can accomplish this task by one of the following options:

## Preparation

This article uses the `random` library for each example. For these code samples to run error-free, add the following snippet to the top of each example.

`import random`

## Method 1: Use random.choice() and items()

This example uses `random.choice()` and `items()` to generate a random Dictionary key:value pair.

```el_list = list(els.items())
random_el = random.choice(el_list)
print(random_el)```

The above code converts the Dictionary of Periodic Table Elements to a List of Tuples and saves it to `el_list`. If output to the terminal, the contents of `el_list` contains the following.

`[('Hydrogen', 'H'), ('Helium', 'He'), ('Lithium', 'Li'), ('Beryllium', 'Be'), ('Boron', 'B'), ('Carbon', 'C'), ('Nitrogen', 'N'), ('Oxygen', 'O'), ('Fluorine', 'F'), ('Neon', 'Ne'), ('Sodium', 'Na'), ('Magnesium', 'Mg'), ('Aluminum', 'Al'), ('Silicon', 'Si'), ('Phosphorus', 'P'), ('Sulfur', 'S'), ('Chlorine', 'Cl'), ('Argon', 'Ar'), ('Potassium', 'K'), ('Calcium', 'Ca'), ('Scandium', 'Sc'), ('Titanium', 'Ti'), ('Vanadium', 'V'), ('Chromium', 'Cr'), ('Manganese', 'Mn')]`

Next, `random.choice()` is called and passed one (1) argument: `el_list`.

The results return a random `Tuple `from the List of Tuples, saves to `random_el `and is output to the terminal.

This code can be streamlined down to the following.

`random_el = random.choice(list(els.items()))`

## Method 2: Use random.choice() and keys()

This example uses `random.choice()` and `keys()` to generate a random Dictionary key.

```random_el = random.choice(list(els.keys()))
print(random_el)```

The above code calls `random.choice()` and passes it one (1) argument: the keys of the `els` Dictionary converted to a List of Tuples.

The result returns a random key, saves to `random_el `and is output to the terminal.

## Method 3: Use random.choice() and dict.values()

This example uses `random.choice()` and `values()` to generate a random Dictionary value.

```random_el = random.choice(list(els.values()))
print(random_el)```

The above code calls `random.choice()` and passes it one (1) argument: the keys of the `els` Dictionary converted to a `List of Tuples`.

The result returns a random value, saves to `random_el `and is output to the terminal.

## Method 4: Use sample()

This example uses the `sample()` function to generate a random Dictionary key.

```from random import sample
random_el = sample(list(els), 1)
print(random_el)```

The above code requires `sample` to be imported from the `random` library.

Then, `sample()` is called and passed two (2) arguments: `els` converted to a `List of Tuples` and the number of random keys to return.

The results save to `random_el` and is output to the terminal.

## Method 5: Use np.random.choice()

This example uses NumPy and `np.random.choice()` to generate a random Dictionary key.

```import numpy as np

random_el = np.random.choice(list(els), 1)
print(random_el)```

This code imports the NumPy library installed above.

Then, `np.random.choice()` is called and passed two (2) arguments: `els` converted to a List of Tuples and the number of random keys to return.

The results save to `random_el` and is output to the terminal.

π‘Note: `np.random.choice()` has an additional parameter that can be passed. This parameter is a `List` containing associated probabilities.

## Bonus:

This code generates a random key:value pair from a list of tuples. When the teacher runs this code, a random question displays on the screen and waits for a student to answer. Press 1 to display the answer, 2 to quit.

```import keyboard
import random
import time

els = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li',
'Beryllium': 'Be', 'Boron': 'B', 'Carbon': 'C',
'Nitrogen': 'N', 'Oxygen': 'O', 'Fluorine': 'F',
'Neon': 'Ne', 'Sodium': 'Na', 'Magnesium': 'Mg',
'Aluminum': 'Al', 'Silicon': 'Si', 'Phosphorus': 'P',
'Sulfur': 'S', 'Chlorine': 'Cl', 'Argon': 'Ar',
'Potassium': 'K', 'Calcium': 'Ca', 'Scandium': 'Sc',
'Titanium': 'Ti', 'Vanadium': 'V', 'Chromium': 'Cr',
'Manganese': 'Mn'}

def quiz():
while True:
k, v = random.choice(list(els.items()))
print(f'\nWhat is the Symbol for {k}?')

if pressed == '1':
elif pressed == '2':
print("Exiting\n")
exit(0)
time.sleep(5)
quiz()```

β¨Finxter Challenge!
Write code to allow the teacher to enter the answer!

## Summary

This article has provided five (5) ways to get a random entry from a Dictionary to select the best fit for your coding requirements.

Good Luck & Happy Coding!