Finding a value in a dictionary, not a key - python

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.

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")

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)
Try it here!
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].

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

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.

Related

How do I get the frequency of my dictionary value as it changes?

I am a novice, just started learning how to program.
I will to ask how do I get the frequency/count of a value changed within a key?
for instance:
user_input= input("Enter a word")
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
so if the user selects coffee, he/she can amend by adding or delete that value.
He/she is then able to view the number of time the key "coffee" is being amended.
I appreciate the prompt responses from everyone! But maybe this example below will be a little more comprehensive.
if user selects coffee, they can either have the option to delete or append new sentence to the existing key.
So for every value that is being deleted or added: it will be recorded
For example: If I will to change the Coffee's value, that will 1, thereafter, if I will to delete the Coffee's value again, it will be the 2nd time I have amend the value within coffee.
output: Revision changed on "Coffee" : 2
I'm not sure if I'm understanding your question correctly, but if I am, then an if statement should do the trick, every time the user picks coffee it'll add one to it's corresponding counter and same thing with tea, then you do whatever you want with those values:
user_input= input("Enter a word")
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
if user_input == "Coffee":
coffee_amend += 1
if user_input == "Tea":
tea_amend += 1
This is my first time ever responding to anything so please tell me if I did anything wrong; I hope you found this helpful!
First modify the structure of the dictionary that you are using like below:
dic = {"Coffee": [["I love coffee."],0], "Tea": [["I love tea."],0]}
As you can see I have maintained, the count of number of times changed and It value at the key.
Now make two functions for changing the value at a particular key and getting the count of number of times value changed at that particular key
def changeKeyValue(dic, key, value):
dic[key][1] += 1
dic[key][0] = value
changeKeyValue(dic,'Coffee',None)
def getNumTimes(dic,key):
return dic[key][1]
Now use these functions to get the result you want :
print("Key value changed", getNumTimes(dic,"Coffee"))
Hope this helped.
I am assuming that you want something that interacts with the user. This is not super elegant but it is easy to understand:
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
cnt_dict = {}
cont = True
while cont == True:
user_input = input("Enter a word")
user_input2 = input('What would you like to do?')
if user_input2 == 'delete':
dict[user_input] = '' #sets the value to empty list
if user_input2 == 'ammend':
user_input3 = input('What would you like to change to?')
dict[user_input] = user_input3
if user_input in cnt_dict.keys():
cnt_dict[user_input] += 1
else:
cnt_dict[user_input] = 1
print(cnt_dict)
input_4 = input('continue? (y/n)')
if input_4 != 'y':
cont = False
cnt_dict is a dictionary which counts the number of times each key is changed. Hopefully this helps. Edit: Obviously there will be problems if you are trying to add things not currently in dict but you can build off this.

How to print take something out of a list and store it elsewhere

I am making a music key theory test.
In order to achieve something else that I won't explain right now here (maybe I will later though if this doesn't work), I need to take the root chord out of the list, store it somewhere else, and call back upon it for the user input when they are asked what key the chords come from.
I don't know how to do this, but I am pretty sure it is possible. I would love it if someone could help me. After I have this problem sorted out I will be much further.
Before, I was trying to find someway to have the actual variable represent the variable, while representing what the variable contains. So then after printing the randomized chords from the variable, the user can input the key from which the chords come from, which I have as the variable. But I don't think that will work.
import random
print('Key Theory Werkout')
Dmajor = {'D','E-','F⌗-','G','A','B-','C⌗dim'}
Gmajor = {'G','A-','B-','C','D','E-','F⌗dim'}
Cmajor = {'C','D-','E-','F','G','A-','Bdim'}
Fmajor = {'F','G-','A-','Bb','C','D-','Edim'}
Bbmajor = {'Bb','C-','D-','Eb','F','G-','Adim'}
Ebmajor = {'Eb','F-','G-','Ab','Bb','C-','Ddim'}
Abmajor = {'Ab','Bb-','C-','Db','Eb','F-','Gdim'}
Dbmajor = {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'}
Cxmajor = {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'}
Gbmajor = {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'}
Fxmajor = {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'}
Bmajor = {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'}
Cbmajor = {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'}
Emajor = {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'}
Amajor = {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'}
questions = [Dmajor, Gmajor, Cmajor, Fmajor, Bbmajor, Ebmajor,
Abmajor, Dbmajor, Cxmajor, Gbmajor, Fxmajor, Bmajor, Cbmajor,
Emajor, Amajor]
print('Difficulty:Easy, Hard')
begin = input("Choose Difficulty:")
if begin == 'easy':
while begin == "easy":
q = random.choice(questions)
qq = random.sample(list(q), 7)
print(qq)
answer = input('Please Provide the key:')
if answer == q
'''HERE IS THE PROBLEM. Lets say the code outputs F, A-, Bb, C, D-
for Dmajor. How can I have the user type in Dmajor and have it
print correct, or incorrect? I am thinking I will have to put .
entire blocks for each question, and then have the easy choose
random out of all of those questions and that will be how I have to
do it. But maybe there is an easier way.
'''
print("correct")
I would like it to tell the user if they are correct or wrong, while keeping the randomness of questions, and chords it spits out exactly the way it is.
What do I need to do?
Maybe you can try using a dictionary to represent your questions, like this:
questions = {
'Dmajor': {'D','E-','F⌗-','G','A','B-','C⌗dim'},
'Gmajor': {'G','A-','B-','C','D','E-','F⌗dim'},
'Cmajor': {'C','D-','E-','F','G','A-','Bdim'},
'Fmajor': {'F','G-','A-','Bb','C','D-','Edim'},
'Bbmajor': {'Bb','C-','D-','Eb','F','G-','Adim'},
'Ebmajor': {'Eb','F-','G-','Ab','Bb','C-','Ddim'},
'Abmajor': {'Ab','Bb-','C-','Db','Eb','F-','Gdim'},
'Dbmajor': {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'},
'Cxmajor': {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'},
'Gbmajor': {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'},
'Fxmajor': {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'},
'Bmajor': {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'},
'Cbmajor': {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'},
'Emajor': {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'},
'Amajor': {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'},
}
Then, you select a random question like this:
key = random.choice(list(questions))
set = questions[key]
sample = random.sample(set, 7)
Now, you only have to check if answer is equal to key.

Lists won't produce result due to it must be a string. 8 Ball Fortune

The problem with my code is that when running it to see if the first word of the question is in the query list. It won't give anything back due to being a int. Can anyone point me towards right direction ?
import random
response = [ 'Yes, of course!',"Without a doubt,yes.",
'For sure!','Ask me later.',
'I am not sure.',
'I will tell you after my nap.',
'No Way!','I do not think so.',
'The answer is clearly NO.']
query = ['Will','Are','Is','Am','Do','Can','May']
# Global lists ^^^
def main(response,query,ran):
# The program that
print('Ask a question that can only be answered in yes or no.')
question = input()
if question(0) in query():
ran(response,query)
res = ran(response,query)
print(res)
again = input('Enter Y or y to play again. Enter N or n to exit.')
if again in ['y','Y']:
main(lists)
else:
print('This program will now close.')
def ran(response,query):
res = random.choice(response)
return res
main(response,query,ran)
The problem lies here question.index(0) in lists. You are comparing apples with pears. index will yield a number and you are comparing it with the actual definition of the lists function. You might want to rethink what you want to compare.
Secondly, you will have extra errors, you are using random.sample in a bad way, you should be doing random.sample(response, 1)[0], I'm presuming you want to pick a random response from that collection.
Thirdly, what is the lists() function supposed to do?

How to print different items depending on a random print in Python?

How to print different items depending on a random print in Python? Here is part of my script.
Mage = "Mage"
Warrior = "Warrior"
Thief = "Thief"
skilltree = (Mage, Warrior, Thief)
print random.choice (skilltree)
Now say it randomly chose Warrior. In my next script it would print 7 skills. But if it were to randomly choose Thief or Mage they would of been 7 completely different skills. So I want the 7 skills you get to depend on the randomly chosen skill tree.
You have done the hard part. Now you just need to map the skills to each category. For instance, using a dictionary:
skills = {'Mage': range(7), 'Warrior': range(7,14), 'Thief': range(14,21)}
choice = random.choice(skilltree)
print skills[choice]
This will print the list of skills you associated with the chosen skilltree. I used range just to illustrate, you could have a list of strings with the skills.
I will just illustrate a little bit further with Paulo's example in case you are not familiar with using a dictionary (and like he said using a dictionary is probably the best choice for a mapping).
MageSkills = ["Mskill1", "Mskill2"]
ThiefSkills = ["Tskill1", "Tskill2"]
WarriorSkills = ["Wskill1", "Wskill2"]
skills = {'Warrior': WarriorSkills, 'Mage': MageSkills, 'Thief': ThiefSkills}
choice = 'Warrior'
print(skills[choice])
The general concept of a solution has been outlined by others, but I think they're missing the key misunderstanding behind your question, which is how to persist something that you randomly chose and printed. As far as that goes, and for understanding this is what I would do:
import random
classes = ("Mage", "Warrior", "Thief")
skill_dictionary = {"Mage": ["Fireball", "Ice Blast"...], "Warrior": [...]} # etc
random_class = random.choice(classes) # Keep a version around for yourself
print random_class # print the version you just saved so you still have a copy
print skill_dictionary[random_class] #Then use the saved version to get the skill list
An important thought distinction to have here is separating getting the data from displaying it. First you randomly choose the data, and only after you already have it do you decide to show it to the user with your print statement.
The dictionary is just a key/value store (something that maps keys(your classes) to values (your skills)). It happens to fit this problem well, but you could implement this in other ways.

Giving Exceptions to a Random Choice

Now I have been trying for fun to make my own version of the game clue, and I cannot seem to find out how do this. I am trying to make it so that if the guess is wrong, it will give a hint from the other guesses that is not the real "killer" and that is not any of their previous guesses. I'll give an example of something similar:
a = input()
b = input()
c = input()
d = input()
e = input()
f = input()
hint = random.choice([a,b,c,d,e,f])
hint != killer
hint != previous_guess
Now I know that the hint != killer and hint != previous_guess doesn't really do anything, as hint is assigned before. I am wondering if there is any way to make it so that it will chose randomly from a variable that is not the killer or a previous guess. Thanks in advance! Oh also I would like to point out that I am using python.
You can use a set and subtract the ones you dont want, e.g.
hint = random.choice(list({a, b, c, d, e, f} - {killer, previous_guess}))
Here is a basic way you could do it. This uses the concept of what is called a list comprehension in order to generate a list in an efficient way. The .format() indicates string formatting, which allows you to pass variables into strings in a variety of formats (docs here, but for now just know that {0} refers to the first argument to format()).
names is generated using the aforementioned list comprehension, and it is syntactically equivalent to:
names = []
for i in range(6):
names.append(raw_input('Enter a name: ')
This pattern is used later to generate your list without the killer nor the previous guess. Happy to explain any parts that don't make sense (thanks to #JonClements for pointing out some oddness I had left in there):
import random
# Choose your names
names = [raw_input('Enter killer name: ') for i in xrange(6)]
# Choose a killer
killer = random.choice(names)
# Run for as many times as you want (here we do 6; could also be len(names)
max_guesses = 6
for guessno in xrange(max_guesses):
guess = raw_input('Guess the killer: ')
# If the guess is not the killer...
if guess != killer:
# This line creates a list that does not include the killer nor the guess
hint = random.choice([n for n in names if n not in [killer, guess]])
print 'Hint, the killer is not {0}'.format(hint)
else:
print 'Correct! The killer is {0}'.format(guess)
break

Categories

Resources