0

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

  • 1
    The word you are looking for is `if`, not "when". – Scott Hunter Nov 21 '22 at 20:01
  • 4
    does [this](https://stackoverflow.com/a/2263826/15521392) help? Accessing keys with `get` and a default value (e.g. "no domain value") if the key is not present. – Rabinzel Nov 21 '22 at 20:02
  • 3
    This is not about JSON. The HTTP response contained a JSON payload, but the `json` method returns an ordinary `dict` value. – chepner Nov 21 '22 at 20:03
  • You are asking about how to work with `dict` objects, not JSON. The fact that the response was JSON encoded (and successfully parsed) is entirely irrelevant to your question – juanpa.arrivillaga Nov 21 '22 at 20:15
  • Yeah, thanks for the tips, guys. I thought I was working with a JSON, I'm still learning, I'm going to study more! – Vinicius Stanula Nov 21 '22 at 20:29

1 Answers1

1

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'))
maxxel_
  • 437
  • 3
  • 13