I have a JSON at ‘https://api.exchangerate.host/symbols’ having data in the form
‘symbols’: {‘AED’: {‘code’: ‘AED’, ‘description’: ‘United Arab Emirates Dirham’}, ‘AFN’: {‘code’: ‘AFN’, ‘description’: ‘Afghan Afghani’}, ……….
In following program, I am unable fix the bug to get may desired output, rather it always provide the same output, ( for any THREE alphabets, as input ) i.e. "There is NO match against the input you provided."
mport requests
#from pprint import PrettyPrinter
#printer = PrettyPrinter()
url = 'https://api.exchangerate.host/symbols'
response = requests.get(url)
data = response.json()
def find_matching_currencies(input_letters):
matching_currencies = []
for code, description in data['symbols'].items():
if isinstance(description, str) and input_letters in description:
matching_currencies.append((description, code))
return matching_currencies
def main():
user_input = input("Please Enter the FIRST THREE Letters of Your Country: ")
matching_currencies = find_matching_currencies(user_input)
if matching_currencies:
print("Following is the result based on your input:")
for description, code in matching_currencies:
print(f'Your Currency name is: {description} and the code for it is: {code}')
else:
print("There is NO match against the input you provided.")
if __name__ == "__main__":
main()
I used to write the program in many ways but unable to get the desired result i.e. If the user type first three ‘alphabet’ of his country then he should get the ‘code’ of the currency along with the ‘description’ from the JSON file in the following format :
print(f’Your Currency name is: {description} and the code for it is: {code}’)
4
Answers
This if statement will never be true, because
description
is a sub-dictionary; it is not a plain string.In your
find_matching_currencies
method yourdiscription
variable holds for example this value:{'code': 'AED', 'description': 'United Arab Emirates Dirham'}
. Thats the cause of your issue.Here is a working version:
Your search criteria don’t make much sense. The ‘description’ value in the JSON response is the proper name of a currency. Taking the first 3 letters of a country name and searching in the description will reveal ambiguous results. For example… What if the user input is FRA? These are the first three letters of FRANCE yet the results wouldn’t have anything to do with that country.
Here’s a simplification of your code which will hopefully make it clearer how you could approach this:
Console:
This may work :