使用try excep查找dict中的键

2024-04-20 10:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的职能是:

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

try/except无效。我试图查看用户输入是否在字典键中,然后返回键和相应的值

如果imp不在字典中,为什么这是一个无限循环?


Tags: inputdictionary字典defprintinp职能try
3条回答

只是

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

您还需要打破while True循环

另外,如果您使用的是py2x,您将希望使用raw_input,而不是{}

也许我误解了一些东西,但是要检查一个值是否是字典键,这很简单:

'key' in dictionary

返回True或{}。在

此外,您甚至可以做如下操作:

^{pr2}$

如果键不在字典中,您将得到字符串"Key not in dictionary",否则您将得到由'key'标记的实际值。在

代码中的listkeys是一个列表,而不是字典。在列表中查找元素不会导致KeyError。在

如果你用的是列表

item in list_name

会给出正确或错误的答案。在

还要将输入修改为raw_input(),使其将字符串视为字符串而不是对象名称。在

尝试使用如下方法:

^{pr2}$

相关问题 更多 >