![]() |
|
[Tut] How to Get a Random Entry from a Python Dictionary - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Get a Random Entry from a Python Dictionary (/thread-99950.html) |
[Tut] How to Get a Random Entry from a Python Dictionary - xSicKxBot - 09-15-2022 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]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:
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]
|