Reputation: 304
Say that I have the following dictionary:
mydict = {"3322": 4 , "3323": 3 , "3324": 5}
Now say that I want to print "3323" once the the user inputs 3. What I've got so far:
printer = input("please enter a number: ")
Now i'm not sure how to use "printer" to print 3323 once the user inputs 3.
Upvotes: 0
Views: 351
Reputation: 6563
Since you are looking for keys (which must be unique) by their corresponding values (that can be repeated more than once in a dictionary,) it is possible for there to be more than one resulting key that maps to a given value.
Fortunately, we can find all of the keys using a list comprehension:
results = [k for k,v in mydict.items() if v == int(printer)]
And of course you can print them all out like so:
print('\n'.join(results))
This way, all of the keys found will be printed (separated by newlines,) and nothing will be printed if nothing is found.
Upvotes: 1
Reputation: 7329
First your dictionary is "backwards", ie what you want to use a key is actually stored a value, flip it around with a dictionary comprehension:
mydict = {v:k for (k,v) in mydict.iteritems()}
Then it is best to capture user input in a while loop:
while 1:
key = input("please enter a number: ")
try:
if int(key) in mydict:
print mydict[int(key)]
break
else:
print "{n} not present!".format(n = key)
except ValueError:
print "please enter a number!"
This way if the user messes up they can try again..
Upvotes: 0