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

sqougxex  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(196)

我试图在下面的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
esyap4oy

esyap4oy1#

从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

相关问题