09-15-2022, 02:08 PM
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 [i]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.[/i]
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 library for each example. For these code samples to run error-free, add the following snippet to the top of each example.
Method 1: Use random.choice() and items()
This example uses and to generate a random Dictionary key:value pair.
The above code converts the Dictionary of Periodic Table Elements to a List of Tuples and saves it to. If output to the terminal, the contents of contains the following.
Next, is called and passed one (1) argument: .
The results return a randomfrom the List of Tuples, saves to and is output to the terminal.
This code can be streamlined down to the following.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLtYPiOZq-BQ%2Fhqdefault.jpg)
Method 2: Use random.choice() and keys()
This example uses and to generate a random Dictionary key.
The above code calls and passes it one (1) argument: the keys of the Dictionary converted to a List of Tuples.
The result returns a random key, saves toand is output to the terminal.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqSEEOOTUrjk%2Fhqdefault.jpg)
Method 3: Use random.choice() and dict.values()
This example uses and to generate a random Dictionary value.
The above code calls and passes it one (1) argument: the keys of the Dictionary converted to a .
The result returns a random value, saves toand is output to the terminal.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FENjl8yKu00M%2Fhqdefault.jpg)
Method 4: Use sample()
This example uses the function to generate a random Dictionary key.
The above code requires to be imported from the library.
Then, is called and passed two (2) arguments: converted to a and the number of random keys to return.
The results save to and is output to the terminal.
Method 5: Use np.random.choice()
This example uses NumPy and to generate a random Dictionary key.
Before moving forward, please ensure the NumPy library is installed. Click here if you require instructions.
This code imports the NumPy library installed above.
Then, is called and passed two (2) arguments: converted to a List of Tuples and the number of random keys to return.
The results save to and is output to the terminal.
Note: https://docs.python.org/3/library/random.html has an additional parameter that can be passed. This parameter is a 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.
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
[i]“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[/i]
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 [i]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.[/i]Code:
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:
- Method 1: Use andCode:
random.choice()Code:items()
- Method 2: Use andCode:
random.choice()Code:keys()
- Method 3: Use https://blog.finxter.com/python-random-module/andCode:
random.choice()Code:values()
- Method 4: Use Code:
sample()
- Method 5: Use Code:
np.random.choice()
Preparation
This article uses the
Code:
randomCode:
import randomMethod 1: Use random.choice() and items()
This example uses
Code:
random.choice()Code:
items()Code:
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
Code:
el_listCode:
el_listCode:
[('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,
Code:
random.choice()Code:
el_listThe results return a random
Code:
TupleCode:
random_elCode:
('Oxygen', 'O')This code can be streamlined down to the following.
Code:
random_el = random.choice(list(els.items()))Method 2: Use random.choice() and keys()
This example uses
Code:
random.choice()Code:
keys()Code:
random_el = random.choice(list(els.keys()))
print(random_el)The above code calls
Code:
random.choice()Code:
elsThe result returns a random key, saves to
Code:
random_elCode:
BerylliumMethod 3: Use random.choice() and dict.values()
This example uses
Code:
random.choice()Code:
values()Code:
random_el = random.choice(list(els.values()))
print(random_el)The above code calls
Code:
random.choice()Code:
elsCode:
List of TuplesThe result returns a random value, saves to
Code:
random_elCode:
SiMethod 4: Use sample()
This example uses the
Code:
sample()Code:
from random import sample
random_el = sample(list(els), 1)
print(random_el)The above code requires
Code:
sampleCode:
randomThen,
Code:
sample()Code:
elsCode:
List of TuplesThe results save to
Code:
random_elCode:
['Carbon']Method 5: Use np.random.choice()
This example uses NumPy and
Code:
np.random.choice()Before moving forward, please ensure the NumPy library is installed. Click here if you require instructions.
Code:
import numpy as np random_el = np.random.choice(list(els), 1)
print(random_el)This code imports the NumPy library installed above.
Then,
Code:
np.random.choice()Code:
elsThe results save to
Code:
random_elCode:
['Chromium' 'Silicon' 'Oxygen']
Note: https://docs.python.org/3/library/random.htmlCode:
np.random.choice()Code:
ListBonus:
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.
Code:
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
[i]“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[/i]

