简体   繁体   中英

Choosing which dictionary to use based on user input in Python

I'm trying to solve an issue in order to be able to teach some skills to my GCSE class this is based on the idea of a currency converter. I have a program that allows me to convert from a single currency using a dictionary to chose the exchange rate based on the currency you want to be converted to.

I have tried to extend this using multiple dictionaries but am unable to get the code to select which dictionary to used based on the user input.

My commented code is below - basically I want to chose which dictionary to use based on the user input for the currency in the first while loop.

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.

Don't try to map to variable names. Just create another level here, add a dictionary holding your currencies:

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},
}

You can then take the keys of the dictionary to make a list of available currencies:

print(list(currencies))

and you can test if the currency exists:

if currency in currencies:

Once a currency is picked, use currencies[currency] to refer to the nested dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM