为了账号安全,请及时绑定邮箱和手机立即绑定

python 3.x - 如何使用带下划线的键访问值

python 3.x - 如何使用带下划线的键访问值

翻过高山走不出你 2021-06-17 22:13:00
每个人。我是 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.


查看完整回答
反对 回复 2021-06-22
  • 1 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号