Python中查找含security_check键的数组元素并解决KeyError问题求助
解决KeyError问题:查找包含指定键的数组元素并提取值
你猜的没错,这个KeyError就是因为数组里的部分元素没有security_check这个键——当你直接用entry["security_check"]去访问时,Python遇到没有该键的元素就会抛出这个错误。另外你的函数里还有两个小问题需要一起修正:
- 函数参数是
json_data,但循环里用了未定义的json_object,参数名不匹配 - 判断条件
if entry["security_check"] in json_object逻辑错误,应该检查该键是否在当前的entry元素里
这里给你两个可行的修正方案:
方案一:检查键是否存在(最直接)
def array_parse_for_item_name(json_data): # 先获取data数组(你的原始数据结构是外层有个data键) for entry in json_data['data']: # 先判断当前元素是否包含security_check键,避免KeyError if 'security_check' in entry: print(f"Item Name: {entry['item_name']}") print(f"Item Stock: {entry['item_stock']}")
方案二:使用get方法(更灵活)
如果担心后续security_check可能有None值的场景,或者想更安全地访问键,可以用字典的get()方法——当键不存在时,它会返回None而不是抛出错误:
def array_parse_for_item_name(json_data): for entry in json_data['data']: # get方法默认返回None,也可以指定默认值比如entry.get('security_check', 'default') if entry.get('security_check') is not None: print(f"Item Name: {entry['item_name']}") print(f"Item Stock: {entry['item_stock']}")
调用函数时,直接传入你的json_data即可:
array_parse_for_item_name(json_data)
这样运行后,就只会输出包含security_check键的元素的item_name和item_stock值啦。
内容的提问来源于stack exchange,提问作者zoenightshade
相关产品推荐
相关产品推荐

