I need the programme to select a random value from the dictionary and ask the user what the key is. The dictionary is a glossary. I want the programme to give the user a definition first.
-
See [How can I extract all values from a dictionary in Python?](https://stackoverflow.com/questions/7002429/how-can-i-extract-all-values-from-a-dictionary-in-python), then [How to randomly select an item from a list?](https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list), then put them together. Breaking your problem down into individual steps is key to problem solving. – glibdud Jul 16 '19 at 20:44
-
Can you give us some lines of code to help you to solve your problem ? – F Blanchet Jul 16 '19 at 20:48
-
The only difference between the two pieces of code is your variable name. Why would you expect it to give a different result? – Acccumulation Jul 16 '19 at 21:02
-
https://docs.python.org/3/library/stdtypes.html#dict.values – benvc Jul 16 '19 at 21:07
-
Welcome to StackOverflow! Please remember to mark an answer as "accepted" if it answers your question. Good luck with your coding! – Nick Reed Jul 17 '19 at 00:33
4 Answers
One way you can approach this is to get a random key from your dictionary first and then simply retrieve the value afterwards. To do this, you can use the random
library and then do the following:
import random
glossary = {
"water": "a transparent, odorless, tasteless liquid, a compound of hydrogen and oxygen",
"wind": "air in natural motion",
"fire": "a state, process, or instance of combustion in which fuel or other material is ignited and combined with oxygen"
}
correctAnswers = 0
totalQuestions = len(glossary)
while correctAnswers < totalQuestions:
# Get a random key and value from the glossary dictionary
word = random.choice(list(glossary.keys()))
definition = glossary[word]
# Present the prompt
print("The definition is:", definition)
answer = input("What word is this? ")
# Determine if answer was correct
if answer.lower() == word:
print("Correct!")
correctAnswers += 1
del glossary[word]
else:
print("Incorrect, try again.")
This will output a random definition from within the glossary and will also give the key that it is mapped by. It will then prompt the user to answer what they think the word is. If they are correct, the definition will be removed from the glossary and another question will be asked if one still exists.
Hopefully this gets you started with what you are trying to do.

- 155
- 8
-
If you take a look at the example above, it will fetch both the word and the definition for you. So you can just choose which one you want to display. – LordOfSun Jul 16 '19 at 21:06
-
I edited my answer to go through each part of the problem. In summary, the program will randomly select a definition for each question and continue to loop until all definitions in the glossary have been correctly answered. – LordOfSun Jul 16 '19 at 21:18
Here's what I came up with:
import random
d = {'Key 1':'Value 1', 'Key 2':'Value 2'}
randomKey = random.choice(list(d.keys()))
print(d[randomKey])
A random value is printed. Hope this helps.
Edit: You copied the code wrong, it should read:
random_key = random.choice(list(glossary))
print('Define: ', glossary[random_key])
input('Press return to see the definition')
print(glossary[random_key])
Make sure you have imported random import random
-
-
In fact, it should be: `random_key = random.choice(list(glossary))` `print('Define: ', glossary[random_key])` `input('Press return to see the definition')` `print(glossary[random_key])` – Jul 16 '19 at 21:01
-
Have you changed your mind? This is what you wrote: I want the programme to give the user a definition, then the user guess the word. – Jul 16 '19 at 22:42
I propose this:
import numpy as np
dict = {"cat" : "a carnivorous mammal (Felis catus) long domesticated as a pet and for catching rats and mice.",
"dog" : "A domesticated carnivorous mammal (Canis familiaris syn. Canis lupus subsp. familiaris) occurring as a wide variety of breeds, many of which are traditionally used for hunting, herding, drawing sleds, and other tasks, and are kept as pets.",
"butterfly" : "Any of numerous insects of the order Lepidoptera, having four broad, usually colorful wings, and generally distinguished from the moths by having a slender body and knobbed antennae and being active during the day."}
length_dict = len(dict)
list_values = list(dict.values())
list_keys = list(dict.keys())
while True:
r = np.random.randint(length_dict)
print("Define: ")
print(list_values[r])
inp = input()
if inp == list_keys[r]:
print("Correct")
else:
print("Wrong")

- 1,299
- 1
- 8
- 29
-
This is a good method but I would change a few things. First off, order in a list is never guaranteed so I would use a tuple instead. Second I would make it so the answer is not case sensitive. So you end up with ```if inp.lower() == list_keys[r].lower():``` – Robert Kearns Jul 16 '19 at 21:11
-
`order in a list is never guaranteed` Yes it is. It's a *list*. Literally, an ordered finite set. You may be thinking of Python's `set` data type. – Silvio Mayolo Jul 16 '19 at 21:31
You can't. Python doesn't support retrieving keys from a dict by their values, since there's no way to guarantee the values are distinct. However, if you flip them (definition is the key, word is the value) it's much easier to do.
From this answer to a similar question, you can use python's random library, coupled with a bit of data manipulation.
To get a list of the python dictionary's keys, you can use list(yourDict.keys()
- then, you can use random.choice()
from the random
library to get a random key. Finally, you can use this random key as an index to d[]
in order to get your result.
import random
d = {'An aquatic animal':'FISH', 'A common pet':'DOG'}
question = random.choice(list(d.keys()))
val = d[question]
print(question)
print(val)
Do note that for the above example, if you really want to store the word as the key, you can set val = random.choice(list(d.keys)))
and question = d[val]
.

- 4,989
- 4
- 17
- 37
-
I figured you might want to do that, and included it in my answer. Finding a random key also means you find a random value, so if you store a random key in a variable and present the user with `d[key]`, it's the same as presenting them a random value. [Randomly selecting a value and then finding its key is not possible in python](https://stackoverflow.com/a/2568694/7431860), because values are not guaranteed to be unique. – Nick Reed Jul 16 '19 at 21:07
-
For that, you just need to switch your print order. `print('Define:', glossary[random_value])` first, and then `print(random_value)` when they press return. – Nick Reed Jul 16 '19 at 22:23
-
You think it's okay to still keep the first line the same? random_value = choice(list(glossary)) ? – Nicole Jul 16 '19 at 22:28
-
Yes, it's fine to leave the first line the same. The random_value still holds a *key* in it, since list(glossary) returns a list of keys, but the code will run as you intended it to. – Nick Reed Jul 16 '19 at 23:28