-2

I want to have the user use input to call variables from a dictionary but I would like a way to check if the value doesn't exist.

example:

dictionary = {'a': 1, 'b': 2, 'c': 3}

chosen = raw_input("choose one:")

if(dictionary[chosen] == true):
   print(chosen)
else: print("Invalid choice")

When I run something like this is always defaults to the else clause. Why is this?

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
Gregory M
  • 13
  • 5
  • 2
    `if chosen in dictionary:` – Wright Apr 09 '17 at 00:45
  • youve no `:` after your `if` statement and `== true` is unecessary, also `true` should be `True` – Craicerjack Apr 09 '17 at 00:47
  • I wrote this as an example, just to show what I'm trying to do I was looking for theories on how to do this if possible. Thanks! – Gregory M Apr 09 '17 at 00:49
  • If you correct the errors in your code, it works so long as the user enters the key and not the value – Craicerjack Apr 09 '17 at 00:53
  • 2
    do you mean check if a key is in a dictionary? in which case this is a dup of [Python: how can I check if the key of an dictionary exists?](http://stackoverflow.com/questions/3845362/python-how-can-i-check-if-the-key-of-an-dictionary-exists). If not that then it is unclear what you are asking. – Tadhg McDonald-Jensen Apr 09 '17 at 00:53
  • pretty much I want a program that does the following: If the item in the dictionary exists print it, if not display an error message. So how do I check this? I already looked at the other questions that were similar but they did not address the exact issue I'm having. – Gregory M Apr 09 '17 at 00:59

1 Answers1

1

If you clean up the syntax errors and use the in keyword, your code works fine:

dictionary = {'a': 1, 'b': 2, 'c': 3}

chosen = raw_input("choose one:")

if chosen in dictionary: #added colon and changed to if chosen in dictionary
    print(chosen + " : " + str(dictionary[chosen])) #changed to bring both key and value because I didn't know which you wanted
else:
    print("Invalid choice") #I added a new line.
Neil
  • 14,063
  • 3
  • 30
  • 51