Posted on Leave a comment

How to Get a Random Entry from a Python Dictionary

5/5 – (1 vote)

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.

('Oxygen', 'O')

This code can be streamlined down to the following.

random_el = random.choice(list(els.items()))
YouTube Video

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.

Beryllium
YouTube Video

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.

Si
YouTube Video

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.

['Carbon']

Method 5: Use np.random.choice()

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

Before moving forward, please ensure the NumPy library is installed. Click here if you require instructions.

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.

['Chromium' 'Silicon' 'Oxygen']

💡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'} print('1 Answer 2 quit')
def quiz(): while True: k, v = random.choice(list(els.items())) print(f'\nWhat is the Symbol for {k}?') pressed = keyboard.read_key() if pressed == '1': print(f'The answer is {v}!') 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!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd
Leave a Reply