-2

My function is:

def searchstock():  
dictionary=calcreturn(dictionize(tickers(openfile()),pairslist()))
inp=raw_input("What is the stock ticker? ")
while True:
    try:
        dictionary[inp]
        break
    except KeyError: 
        print("Ticker not found. Please input again ")

print(inp, dictionary[inp])

the try/except doesnt work. I'm trying to see if a user input is in the dictionary keys and then return the key and respective value

If imp is not in the dictionary, why would this be an infinite loop?

3 Answers3

2

just

inp=raw_input("What is the stock ticker? ")
try:
   dictionary[inp]
   break; #exit loop
except KeyError:
   print "Nope!"

you will also need to break out of your while True loop

also if you are using py2x you will want to use raw_input instead of input

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

listkeys in your code is a list and not a dictionary. Finding an element in a list will not give you a KeyError.

If you are using lists,

item in list_name

will give either True or False.

Also modify your input to raw_input() so that it considers strings as strings and not as object names.

Try using something like the following:

try:
    dictionary_name[key]
except KeyError:
    #do something
    print "Key Error"
Alagappan Ramu
  • 2,270
  • 7
  • 27
  • 37
  • I changed it to get rid of the list and just search if the input is in the dictionary – user2356391 May 06 '13 at 23:35
  • i still get NameError: name 'BIG' is not defined when i input "BIG" for input (and BIG is int he keys of the dictionary) – user2356391 May 06 '13 at 23:36
  • @user2356391 when you do a normal 'input' in Python, if you enter a value like 'BIG' it is considered to be an object name. Here it is not defined. So as suggested by JoranBeasley change it to raw_input() and your code will work like a charm. – Alagappan Ramu May 06 '13 at 23:40
-1

Maybe I'm misunderstanding something here, but to check if a value is a dictionary key, it's very simple:

'key' in dictionary

which returns True or False.

Additionally, you could even do something like:

mydictionary.get('key', 'Key not in dictionary')

And if the key isn't in the dictionary, you'll get the string "Key not in dictionary", otherwise you'll get the actual value marked by 'key'.

jdotjdot
  • 16,134
  • 13
  • 66
  • 118
  • There could be a possible bug here if the dictionary contains 'Key not in dictionary' itself as a value. – Alagappan Ramu May 06 '13 at 23:35
  • This was just an example. And since we're talking about stock tickers, I highly doubt there would be a stock ticker `"Key not in dictionary"` in that dictionary. – jdotjdot May 07 '13 at 02:08