简体   繁体   中英

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.

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.

Since you want to perform lookups in both directions ie 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 (eg 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 .

EDIT 2:

Here is a possible implementation of my first idea, as requested:

from random import choice

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

...
pair = choice(list(alphabet.items()))
key = choice(pair)
value = pair[0] if key == pair[1] else pair[1]
print('Guess corresponding value', key)
input('Press return to see corresponding value')
print(value)

I hope it is clear, why this solution is less elegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM