Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Randomly display either key or value from dictionary; followed by it's corresponding paired item

This is my first post. I’m hoping someone would kindly help me.

I’m looking to create a program, to at random display either a dictionary key or value, then following user input such as a key pressed to then show the key or values corresponding item.

A dictionary will store values that represent some letters in the alphabet and their corresponding numerical position.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

alphabet = {'1':'A','2':'B','3':'C','4':'D'} 

This code will give the user a number, then after pressing return it will display the corresponding letter in the alphabet.

random_selection = choice(list(alphabet))
print('Guess corresponding value', random_selection)
    input('Press return to see corresponding value')
    print(alphabet[random_selection])

How can I code the program to randomly pick either a number or letter? For example, it may instead show the letter B, then 2 once the user has pressed return.

I would next create a loop so the program runs continuously but I’m confident I can already do this part.

>Solution :

Since you want to perform lookups in both directions i.e. find keys by their values too, a dictionary is not the way to go, since it is bad for that inverse lookup. I would probably store this alphabet as a list of 2-tuples instead, then pick one of them using the choice function and then pick either the first or the second element of the tuple randomly again (e.g. using that same choice function.

You can convert the dictionary to a list of tuples like this:

list(alphabet.items())

EDIT:
Instead of using choice a second time, you could do this:

from random import choice, sample

alphabet = {'1':'A','2':'B','3':'C','4':'D'}

...
pair = choice(list(alphabet.items()))
key, value = sample(pair, k=2)
print('Guess corresponding value', key)
input('Press return to see corresponding value')
print(value)

The sample function returns a randomly shuffled sub-sequence of length k.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading