Catch KeyError in Python

前端 未结 7 1850
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 14:33

If I run the code:

connection = manager.connect(\"I2Cx\")

The program crashes and reports a KeyError because I2Cx doesn\'t exist (it should be

7条回答
  •  梦谈多话
    2021-02-01 14:49

    You can also try to use get(), for example:

    connection = manager.connect.get("I2Cx")
    

    which won't raise a KeyError in case the key doesn't exist.

    You may also use second argument to specify the default value, if the key is not present.

提交回复
热议问题