如何用三元条件表达式检测Python字典中缺失的键值对
问题:处理字典中缺失嵌套键的取值问题
场景说明
我会收到两种Python字典:
- 包含
portal键的字典:
data = { "Other_Key":"Other_Value", "portal": { "isHosted": False, "portalServer": [ { "type": "PHP", "itemID": "hshshdkdkd" }, { "type": "ASP", "itemID": "5s55s5s5s" } ] }, "Other_Key":"Other_Value" }
- 不包含
portal键的字典:
data = { "Other_Key_1":"Other_Value", "Other_Key_3":"Other_Value" }
我需要获取portal下isHosted的值,最初用了这段三元表达式:
status = data['portal']['isHosted'] if data['portal'] != "" else "NA" print(status)
这段代码在字典有portal键时能正常运行,但没有portal键时会抛出KeyError:
Traceback (most recent call last):
File "main.py", line 5, in
status = data['portal']['isHosted'] if data['portal'] != "" else "NA"
KeyError: 'portal'
现在需要解决键缺失时的报错,正确获取目标值或返回替代值。
解决方案
这里有几种可靠的处理方式:
方法1:使用字典的get()方法(推荐)
dict.get(key, 默认值)可以在键不存在时返回指定默认值,嵌套结构可以逐层调用:
status = data.get('portal', {}).get('isHosted', 'NA') print(status)
- 第一层
data.get('portal', {}):如果data里没有portal键,返回空字典{} - 第二层
.get('isHosted', 'NA'):如果portal字典里没有isHosted,或者上层返回了空字典,就返回'NA'
方法2:先判断键是否存在
用in关键字先检查portal是否在字典中,避免直接取值抛出异常:
if 'portal' in data and 'isHosted' in data['portal']: status = data['portal']['isHosted'] else: status = 'NA' print(status)
方法3:捕获KeyError异常
通过try-except块捕获可能的键缺失异常:
try: status = data['portal']['isHosted'] except KeyError: status = 'NA' print(status)
内容的提问来源于stack exchange,提问作者GISGUY
相关产品推荐
相关产品推荐

