每个人。我是 python 的新手,我遇到了一个问题,我可以获取包含下划线的键的值。我有从磁盘加载的以下 JSON 文件。除了键中有下划线的值之外,我可以访问其他值cad_id{"meta": { "summary": "devices are stored here"},"devices": [ { "type": "printer device", "id": "1", "name": "storage_printer", "cad_id": "printer" }, { "type": "email device", "id": "1497041417932", "name": "email", "cad_id": "tfd04", }, { "type": "zone device", "id": "1497041431054", "name": "Page", "cad_id": "page1", }]}这是我到目前为止所拥有的。似乎使用下划线访问密钥的唯一方法是如果我测试它并且我不明白为什么我不能只是做device['cad_id']并获得价值。我不确定我做错了什么,如果有人能告诉我发生了什么以便我理解它,我将不胜感激。感谢您的时间。import socketimport jsondef load_config(): filepath = "/var/www/html/fac3-config.json" with open(filepath) as file_object: config = json.load(file_object) return configdef get_device_by_cad_id(cad_id, config): devices = config["devices"] for device in config["devices"]: #print(device['cad_id']) -- this doesn't work print(device['id']) #this works # this is the only way that I can access the value of cad_id # and I don't understand why #if "cad_id" in device: # if device['cad_id'] == cad_id: # return device['id']config = load_config()device_id = get_device_by_id("page1", config)print(device_id)当我删除打印 cad_id 的注释时,出现以下错误Traceback (most recent call last):File "trigger_hub.py", line 23, in <module> device_id = get_device_by_cad_id("page1", config)File "trigger_hub.py", line 13, in get_device_by_cad_id print(device['cad_id']) KeyError: 'cad_id'
1 回答

不负相思意
TA贡献1777条经验 获得超10个赞
可能是您cad_id在某些记录中没有条目,这就是您可能会收到异常的原因。
您可以使用dict.get()返回 None (或提供的默认值)的方法,而不是通过 访问密钥[],如下所示:
print(device.get('cad_id'))
# or
print(device.get('cad_id', "No cad_id for this record"))
或者,KeyError如果没有cad_id.
添加回答
举报
0/150
提交
取消