我是 Python 新手,我的代碼需要一些支持。我正在使用一些通用 API 來接收以 JSON 格式返回的有關網絡設備的信息這是我的代碼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 得到以下輸出(部分輸出)這里的問題是輸出在一些包含多個字典的列表中,其中一些不提供 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 等的初始結果,然后在沒有這個鍵的情況下點擊字典我嘗試了一些 True/False 邏輯或 if key['deviceIP'] 在邏輯中但對我不起作用。您能否提一些建議?
2 回答

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
您可以先檢查然后打印,如下所示:
if 'deviceIP' in key: print(key['deviceIP'])
或者,您可以使用get(key,default_value)方法dictionary
:
print(key.get('deviceIP',"No deviceIP"))
添加回答
舉報
0/150
提交
取消