如何循环遍历作为值嵌套在 json 文件中的字典的值?

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

我试图循环访问以下 json 文件的字典中“Location”键的值,并查找特定位置的条目数。我怎么能这么做呢?我的循环无法正常工作,因为它要么计算所有条目,无论位置是什么,要么以“TypeError:列表索引必须是整数或切片,而不是 str”结束。

我的代码:

import requests

def count_jobs_by_location(location):
    api_url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/labs/module%201/Accessing%20Data%20Using%20APIs/jobs.json"
    response = requests.get(api_url)
    if response.ok:
        data = response.json()
        count = 0
        for job in data["jobs"]:
            if job["Location"].lower() == location.lower():
                count += 1
        return count
    else:
        return None

python json dictionary nested-loops
1个回答
0
投票

从 for 循环中删除

["jobs"]
。您有字典列表,因此不要使用字符串作为索引:

import requests


def count_jobs_by_location(location):
    api_url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/labs/module%201/Accessing%20Data%20Using%20APIs/jobs.json"
    response = requests.get(api_url)
    if response.ok:
        data = response.json()
        count = 0
        for job in data: # <-- remove ["jobs"] here!
            if job["Location"].lower() == location.lower():
                count += 1
        return count

print(count_jobs_by_location("Los Angeles"))

打印:

640
© www.soinside.com 2019 - 2024. All rights reserved.