Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If python doesn't find certain value inside JSON, append something inside list

I’m making a script with Python to search for competitors with a Google API.

Just for you to see how it works:

First I make a request and save data inside a Json:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    # make the http GET request to Scale SERP
    api_result = requests.get('https://api.scaleserp.com/search', params)

    # Save data inside Json
    dados = api_result.json()

Then a create some lists to get position, title, domain and things like that, then I create a loop for to append the position from my competitors inside my lists:

# Create the lists
    sPositions = []
    sDomains = []
    sUrls = []
    sTitles = []
    sDescription = []
    sType = []

    # Create loop for to look for information about competitors
    for sCompetitors in dados['organic_results']:
        sPositions.append(sCompetitors['position'])
        sDomains.append(sCompetitors['domain'])
        sUrls.append(sCompetitors['link'])
        sTitles.append(sCompetitors['title'])
        sDescription.append(sCompetitors['snippet'])
        sType.append(sCompetitors['type'])

The problem is that not every bracket of my Json is going to have the same values. Some of them won’t have the "domain" value. So I need something like "when there is no ‘domain’ value, append ‘no domain’ to sDomains list.

I’m glad if anyone could help.

Thanks!!

>Solution :

you should use the get method for dicts so you can set a default value incase the key doesn’t exist:

for sCompetitors in dados['organic_results']:
    sPositions.append(sCompetitors.get('position', 'no position'))
    sDomains.append(sCompetitors.get('domain', 'no domain'))
    sUrls.append(sCompetitors.get('link', 'no link'))
    sTitles.append(sCompetitors.get('title', 'no title'))
    sDescription.append(sCompetitors.get('snippet', 'no snippet'))
    sType.append(sCompetitors.get('type', 'no type'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading