Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Get a Random Entry from a Python Dictionary

#1
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



https://www.sickgaming.net/blog/2022/09/...ictionary/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Dictionary of Lists to DataFrame – Python Conversion xSicKxBot 0 1,379 04-17-2023, 03:46 AM
Last Post: xSicKxBot
  [Tut] How I Built an English Dictionary App with Django xSicKxBot 0 1,550 03-29-2023, 04:46 AM
Last Post: xSicKxBot
  [Tut] Can a Python Dictionary Have a List as a Value? xSicKxBot 0 1,164 10-15-2022, 08:22 AM
Last Post: xSicKxBot
  [Tut] Python Print Dictionary Values Without “dict_values” xSicKxBot 0 1,362 10-12-2022, 02:48 AM
Last Post: xSicKxBot
  [Tut] Python Print Dictionary Without One Key or Multiple Keys xSicKxBot 0 1,255 10-10-2022, 08:56 PM
Last Post: xSicKxBot
  [Tut] 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python xSicKxBot 0 1,222 09-27-2022, 10:20 AM
Last Post: xSicKxBot
  [Tut] How to Find the Most Common Element in a Python Dictionary xSicKxBot 0 1,096 09-09-2022, 12:16 PM
Last Post: xSicKxBot
  [Tut] How to Increment a Dictionary Value xSicKxBot 0 1,202 07-22-2022, 10:33 PM
Last Post: xSicKxBot
  [Tut] Convert CSV to Dictionary in Python xSicKxBot 0 1,251 06-19-2022, 04:13 AM
Last Post: xSicKxBot
  [Tut] How to Save a Dictionary to a File in Python xSicKxBot 0 1,258 06-15-2022, 03:15 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:

Forum software by © MyBB Theme © iAndrew 2016