Python循环无法正确遍历字典

2024-09-28 18:57:41 发布

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

我正在为我的个人理财项目工作,我试图让用户能够选择他们希望交易的货币。我试图进行错误处理,如果他们输入的键在字典中不存在,它会显示一条消息并关闭程序。但现在,即使我输入了正确的键,它仍然会关闭

print("Currency's supported: USD, EUR, CAN, YEN, GBP")
currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()


#currencySYM is a dictionary of currency ticker symbols and currency symbols
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}
#the for loop takes the input from Currencycheck and applies the correct symbol to the letters
for key in currencySYM:
    if currencyCheck == key:
        currencyCheck = currencySYM[key]

    elif currencyCheck != key:
        print("Make sure you type the correct three letter symbol.")
        exit()

如果我取出else语句,它可以工作,但不符合预期,我可以键入任何单词,它不必是键,它会将它分配给变量,甚至不检查它是否作为键存在于字典中


Tags: thetokeyyouinput字典eurcan
3条回答

您不希望在检查第一个键后立即跳出。一个解决办法可能是

found = False

for key in currencySYM:
    if currencyCheck == key:
        currencyCheck = currencySYM[key]
        found = True

if !found:
    print("Make sure you type the correct three letter symbol.")
    exit()

当然,更好的方法是检查键是否在字典中:

if currencyCheck in currencySYM:
    currencyCheck = currencySYM[key]
else:
    print("Make sure you type the correct three letter symbol.")
    exit()

您正在检查字典中的每个键是否都已输入,这是不可能的。您可以通过在if子句末尾添加break语句轻松解决此问题:

 if currencyCheck == key:
    currencyCheck = currencySYM[key]
    # found the key, so stop checking
    break

在任何情况下,此代码都不是很pythonic,您可以用整个循环替换此代码,如果dict中没有键,则将返回None:

currencyCheck = currencySYM.get(key,None)
if not currencyCheck:
    print("Make sure you type the correct three letter symbol.")
    exit()

如果要检查给定词典中是否存在key,可以执行此操作key in dict

currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}
if currenyCheck in currencySYM:
    currencyCheck = currencySYM[key]
else:
    exit()

或者您可以使用.get()

currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}

currencyCheck=currencySYM.get(currencyCheck,exit())

Dictionaries are unordered - since the values in the dictionary are indexed by keys, they are not held in any particular order, unlike a list, where each item can be located by its position in the list.

相关问题 更多 >