在 JSON 文件中搜索数据并使用 Python 显示它

问题描述 投票:0回答:1

我在“https://api.exchangerate.host/symbols”处有一个 JSON,其数据格式为

'symbols': {'AED': {'code': 'AED', 'description': '阿联酋迪拉姆'}, 'AFN': {'code': 'AFN', 'description': '阿富汗阿富汗'},..........

在以下程序中,我无法修复错误以获得所需的输出,而是始终提供相同的输出(对于任何三个字母作为输入),即“与您提供的输入不匹配。”

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()

我曾经用多种方式编写程序,但无法获得所需的结果,即如果用户输入他所在国家/地区的前三个“字母”,那么他应该从 JSON 中获取货币的“代码”以及“描述”文件格式如下: print(f'您的货币名称是:{description},其代码是:{code}')

python json dictionary search using
1个回答
0
投票
for code, description in data['symbols'].items():
    if isinstance(description, str) and input_letters in description:

这个 if 语句永远不会为真,因为

description
是一个子词典;它不是一个普通的字符串。

"symbols": {
    "AED":{"description":"United Arab Emirates Dirham","code":"AED"},
    "AFN":{"description":"Afghan Afghani","code":"AFN"},
    "ALL":{"description":"Albanian Lek","code":"ALL"},
    "AMD":{"description":"Armenian Dram","code":"AMD"},
    "ANG":{"description":"Netherlands Antillean Guilder","code":"ANG"},
    ...
 }
© www.soinside.com 2019 - 2024. All rights reserved.