我是 Python 新手,我的代碼需要一些支持。我正在使用一些通用 API 來接收以 JSON 格式返回的有關(guān)網(wǎng)絡(luò)設(shè)備的信息這是我的代碼def device_config(): init = login() vedge_api = os.path.join(vmanage_url, 'dataservice/system/device/vedge') get = token[vmanage_url].get(vedge_api, verify=False) device_inventory = json.loads(get.content) inventory_json = device_inventory['data'] print(inventory_json)我從 inventory_json 得到以下輸出(部分輸出)這里的問題是輸出在一些包含多個(gè)字典的列表中,其中一些不提供 deviceIP 的鍵值for key in inventory_json: print(key['deviceIP'])... print(key['deviceIP'])... 10.10.1.63 10.10.1.60 10.10.1.61 10.10.1.62 Traceback (most recent call last): File "<stdin>", line 2, in <module> KeyError: 'deviceIP'所以我得到了 10.10.1.63 等的初始結(jié)果,然后在沒有這個(gè)鍵的情況下點(diǎn)擊字典我嘗試了一些 True/False 邏輯或 if key['deviceIP'] 在邏輯中但對(duì)我不起作用。您能否提一些建議?
2 回答

慕萊塢森
TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以先檢查然后打印,如下所示:
if 'deviceIP' in key: print(key['deviceIP'])
或者,您可以使用get(key,default_value)方法dictionary
:
print(key.get('deviceIP',"No deviceIP"))

ITMISS
TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用以下方法檢查密鑰是否存在:
if 'deviceIP' in key: print(key['deviceIP'])
添加回答
舉報(bào)
0/150
提交
取消