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}')
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:
import requests
URL = 'https://api.exchangerate.host/symbols'
def find_matching_currencies(currency):
values = []
with requests.get(URL) as response:
response.raise_for_status()
j = response.json()
if j['success']:
for k, v in j['symbols'].items():
if currency in (d := v['description']).lower():
values.append((d, k))
return values
currency = input('Enter part of a currency name: ').lower()
print(*find_matching_currencies(currency), sep='\n')
Console:
Enter part of a country name: fra
('Burundian Franc', 'BIF')
('Congolese Franc', 'CDF')
('Swiss Franc', 'CHF')
('Djiboutian Franc', 'DJF')
('Guinean Franc', 'GNF')
('Comorian Franc', 'KMF')
('Rwandan Franc', 'RWF')
('CFA Franc BEAC', 'XAF')
('CFA Franc BCEAO', 'XOF')
('CFP Franc', 'XPF')