mrOlympia
mrOlympia

Reputation: 351

Handle missing key from dict

I have this script which I use to pull in some data from an API call.

# list of each api url to use
link =[]
#for every device id , create a new url link into the link list
for i in deviceIDList:
    link.append('https://website/v2/accounts/accountid/devices/'+i)

#create a list with all the different requests

deviceReq = []
for i in link:
    deviceReq.append(requests.get(i, headers=headers).json())


# write to a txt file
with open('masterSheet.txt', 'x') as f:
    for i in deviceReq:
        devices =[i['data']]
        for x in devices:
            models = [x['provision']]
            for data in models:
              sheet=(data['endpoint_model']+" ",x['name'])
              f.write(str(sheet)+"\n")

Some devices do not have the provision key.

Here is some sample data looks like from a device that is different.

Let's say I want to grab the device_type key value instead if provision key is non-existent.

"data": {
        "sip": {
            "username": "xxxxxxxxxxxxxxxx",
            "password": "xxxxxxxxxxxxxxxx",
            "expire_seconds": xxxxxxxxxxxxxxxx,
            "invite_format": "xxxxxxxxxxxxxxxx",
            "method": "xxxxxxxxxxxxxxxx",
            "route": "xxxxxxxxxxxxxxxx"
        },

        "device_type": "msteams",
        "enabled": xxxxxxxxxxxxxxxx,
        "suppress_unregister_notifications": xxxxxxxxxxxxxxxx,
        "owner_id": "xxxxxxxxxxxxxxxx",
        "name": "xxxxxxxxxxxxxxxx", 
    }

How do I cater for missing keys?

Upvotes: 0

Views: 269

Answers (1)

KrisRogo
KrisRogo

Reputation: 120

You can use .get(key, defualt_value) to get the value from a dict, or if one is not present it will use the default like this:

provision = x.get('provision', None)
if provision is None:
    provision = x.get('device_type')
models = [provision]

or if you prefer you can do the same on one line and without the extra if or assignment (though some people might find it more difficult to read and understand.

models = [x.get('provision', x.get('device_type'))]

Upvotes: 1

Related Questions