Home > Software engineering >  How do I give a default value to a string that requires a Python response where the response is None
How do I give a default value to a string that requires a Python response where the response is None

Time:09-02

I am trying to write a Python dictionary from a Python requests response. However, the value of the key depends on another value from the JSON object returned, which, for some responses, is "None". The script works fine but the only issue is when the value returned is "None". What I'm trying to achieve is that the value defaults to a certain string when the value of the requested key is "None". For my case, when the uid value is 'None' it returns the string with "None" appended like so https://registry.nbnatlas.org/public/show/None

d = requests.get(dataset_url)

    output = d.json()

owner_url = f"https://registry.nbnatlas.org/public/show/{output.get('provider', {}).get('uid')}" or "https://registry.nbnatlas.org/datasets"

Here is an example response with the keys in place

"provider": {
    "name": "Caring for God’s Acre",
    "uri": "https://registry.nbnatlas.org/ws/dataProvider/dp238",
    "uid": "dp238"
  },

Some responses do not have the provider key

Instead of returning https://registry.nbnatlas.org/public/show/None, I'd want it to default to https://registry.nbnatlas.org/datasets Any way around this?

CodePudding user response:

just use a simple if statement

owner_url = "https://registry.nbnatlas.org/datasets"
if output.get('provider', {}).get('uid') is not None:
   owner_url = f"https://registry.nbnatlas.org/public/show/{output.get('provider', {}).get('uid')}"
   

CodePudding user response:

You can use a ternary operator combined with dict.get:

uid = output.get('provider', {}).get('uid')
owner_url = f"https://registry.nbnatlas.org/public/show/{uid}" if uid is not None else "https://registry.nbnatlas.org/datasets"

Which is the same as:

# Line 1
if 'provider' in output:
    if 'uid' in output['provider']:
        uid = output['provider']['uid']
    else:
        uid = None
else:
    uid = None

# Line 2
if uid is not None:
    owner_url = f"https://registry.nbnatlas.org/public/show/{uid}"
else:
    owner_url = "https://registry.nbnatlas.org/datasets"
  • Related