我正在尝试解决一个问题,以便能够向我的GCSE课程教授一些技能,这是基于货币转换器的想法。我有一个程序,允许我使用字典从单一货币转换,以根据您要转换为的货币选择汇率。
我尝试使用多个词典扩展它,但无法根据用户输入获取代码来选择使用哪个词典。
我的注释代码如下 - 基本上我想根据第一个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.
答案 0 :(得分:3)
不要尝试映射到变量名称。只需在此创建另一个级别,添加一个包含您的货币的字典:
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]
来引用嵌套词典。