Home > Back-end >  If python doesn't find certain value inside JSON, append something inside list
If python doesn't find certain value inside JSON, append something inside list

Time:11-22

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:

    # 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!!

CodePudding user response:

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'))
  • Related