如何用最少的行寫出以下內容?
if a in dict:
if b in dict[a]:
if c in dict[a][b]:
if d in dict[a][b][c]:
print("Value = ", dict[a][b][c][d])
使用 python 3.10
uj5u.com熱心網友回復:
建議使用try/except塊而不是檢查每個鍵是否存在。在你的情況下,我會去:
try:
print("Value = ", dict[a][b][c][d])
except KeyError as e:
print(f"Missing key: {e}")
uj5u.com熱心網友回復:
您可以使用 AND 運算子將所有這些組合在一行中:
if a in dct and b in dct[a] and c in dct[a][b] and d in dct[a][b][c]:
print("Value = ", dct[a][b][c][d])
但正如另一個答案所說,最好的做法是使用 try/except。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392967.html
上一篇:如何驗證表中捕獲的傳入空欄位
下一篇:無法向JSON檔案添加/追加元素
