根据 Python 中的用户输入选择要使用的词典

Choosing which dictionary to use based on user input in Python

我正在尝试解决一个问题,以便能够向我的 GCSE 教授一些技能 class 这是基于货币转换器的想法。我有一个程序,允许我使用字典从单一货币进行转换,以根据要转换为的货币选择汇率。

我尝试使用多个词典来扩展它,但无法根据用户输入select获取要使用哪个词典的代码。

我的评论代码如下 - 基本上我想根据用户在第一个 while 循环中输入的货币来选择要使用的字典。

GBP={"USD":1.64,"EUR":1.21,"YEN":171.63}
USD={"GBP":0.61,"EUR":0.73,"YEN":104.27}
EUR={"GBP":0.83,"USD":1.36,"YEN":141.79}
currencyList=("GBP","EUR","USD","YEN")
#Sets up the dictonaries of conversion rates and validation list for acceptable currencies

while True:
    rate=input("What currency do you require to convert to?\n")
    if rate in GBP:
        #####This is where I have the issue - this code currently works but only for converting from GBP (using the GBP dictonary),
        #####I want to change the 'GBP' to use whatever dictonary corresponds to the value entered for currency
        #####in the loop above.

不要尝试映射到变量名。只需在这里创建另一个级别,添加一个包含您的货币的字典:

currencies = {
    'GBP': {"USD":1.64,"EUR":1.21,"YEN":171.63},
    'USD': {"GBP":0.61,"EUR":0.73,"YEN":104.27},
    'EUR': {"GBP":0.83,"USD":1.36,"YEN":141.79},
}

然后您可以使用字典的键来列出可用货币:

print(list(currencies))

你可以测试货币是否存在:

if currency in currencies:

选择货币后,使用 currencies[currency] 引用嵌套字典。