Search code examples
pythonjsonapidictionarynested-loops

How to loop through the values of the dictionaries which are nested as values in a json file?


I'm trying to loop through the values of "Location" key in the dictionaries of the following json file and find the number of entries for a specific location. How could I do that? My loop isn't working properly as it's either counting all the entries regardless what the location is or was ending up with a "TypeError: list indices must be integers or slices, not str".

My code:

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


Solution

  • Remove the ["jobs"] from the for-loop. You have list of dictionaries so don't use string as an index:

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

    Prints:

    640