小能豆

How to Track Absence of Key Value Pairs in a Python Dictionary Using Ternary Conditional

py

I am receiving two types of dictionary from requesters. some of them has an specific key called portal and some of the no like:

data = {
"Other_Key":"Other_Value",

"portal": {
    "isHosted": False,
    "portalServer": [
        {
            "type": "PHP",
            "itemID": "hshshdkdkd"
        },
        {
            "type": "ASP",
            "itemID": "5s55s5s5s"
        }
    ]
},
 "Other_Key":"Other_Value"
}

or in another format, simply like like this:

data = {
  "Other_Key_1":"Other_Value",
  "Other_Key_3":"Other_Value"
}

Now I want to grab the value of Portal so I used this ternary one line solution to check the existing of Portal in dictionary

status = data['portal']['isHosted'] if data['portal'] != "" else "NA"
print(status)

this is working fine as long as there is a portal node in the data but when is not contain the portal I am getting this error:

Traceback (most recent call last): File “main.py”, line 5, in status = data[‘portal’][‘isHosted’] if data[‘portal’] != “” else “NA” KeyError: ‘portal’


阅读 96

收藏
2023-12-24

共1个答案

小能豆

You are getting a KeyError because you are trying to access the 'portal' key directly without checking if it exists in the dictionary. To avoid the error, you should first check if the key 'portal' is present in the dictionary before attempting to access its values. Here’s an example using an if statement:

if 'portal' in data:
    status = data['portal']['isHosted']
else:
    status = "NA"

print(status)

This way, you check if the key 'portal' is present in the dictionary data. If it is, you can access the value of 'isHosted'. If it’s not present, you set status to “NA” or any other default value you prefer.

Alternatively, you can use the get method to retrieve the value with a default value if the key is not present:

status = data.get('portal', {}).get('isHosted', 'NA')
print(status)

In this case, if 'portal' is not present in data, it returns an empty dictionary, and then if 'isHosted' is not present in the inner dictionary, it returns the default value 'NA'.

2023-12-24