Python-在数组中搜索特定值

时间:2019-10-16 17:37:40

标签: json python-3.x

我正在使用Pythonrequests库来调用API,以获取一些信息。到目前为止,一切都很好。代码运行正常,响应成功:

请求:

def countries():
    # Application header
    header = {
        'Authorization': '123456789',
        'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
    }
    # Make the request and return the country code
    request_url = requests.get(
        'https://endpoint/api/Countries', headers=header)

    countries_dictionary = request_url.json()

countries()

我将响应存储到变量中并将其编码为JSON。当我打印变量的值时,结果如下:

代码:

print(countries_dictionary)

回复:

[
{'CountryId': 1, 'CountryName': 'Belgium', 'Abbreviation': 'B'}, 
...............................................................
...............................................................
{'CountryId': 26, 'CountryName': 'Great Britain', 'Abbreviation': 'GB'}
]

基于以方括号开头的结果,响应为列表。根据{{​​1}}和Python之间的等效项,列表被转换为数组。但是,如果我要提取第一个键的值,则会收到一条错误消息:

代码

JSON

错误:

  

文件“ c:/ Python 3.7 / api.py”,第49行,在某些国家/地区       针对country_dictionary ['CountryId']中的国家/地区:   TypeError:字符串索引必须为整数

我知道索引由整数数据类型表示,并且由于我得到的响应没有任何父节点,所以我有点迷失了方向,不知道下一步如何进行。到目前为止,我在Stackoverflow或任何其他网站上发现的任何内容都无法解决问题。有提示吗?

编辑:

for country in countries_dictionary['CountryId'][0]:
    if country['CountryId']=='1':
        print('Test')

1 个答案:

答案 0 :(得分:2)

根据您的词典的示例列表,您的代码中有几个错误

  • 您不需要[0]索引,因为您可以遍历列表
  • 您无法在for循环定义中指定['CountryId']
  • ['CountryId']的字典值是整数,而不是字符串

    但这应该可以解决问题

countries_dictionary = [{'CountryId': 1, 'CountryName': 'Belgium', 'Abbreviation': 'B'}, 
                        {'CountryId': 26, 'CountryName': 'Great Britain', 'Abbreviation': 'GB'}]
for country in countries_dictionary:
    if country['CountryId']==1:
        print('Test')