如何檢查 Python 字典中是否存在某個鍵

了解如何檢查 Python 字典中是否存在某個鍵。比較 in 運算子、get() 方法、setdefault 和處理 KeyError 例外。

在編輯器中嘗試此解決方案

概述

與動態填充的字典互動時(例如解析使用者參數、配置覆蓋、API 記錄或 JSON 有效負載),嘗試使用不存在的鍵檢索值將引發“KeyError”並使應用程式崩潰。因此,實施防禦性檢查至關重要。

檢查鍵是否存在的最直接、Pythonic、最快的方法是使用「in」成員運算子:「if key in my_dict:」。如果找到鍵,則此表達式傳回“True”,否則傳回“False”。在底層,Python 字典是使用雜湊表實現的,使成員資格檢查高度最佳化,平均時間複雜度為 O(1)。

或者,如果您想要檢索鍵的值,但在鍵遺失時回退到預設值,則可以使用 .get(key, default) 方法。如果鍵存在,則傳回值;如果沒有,它會傳回您的預設值(如果省略則傳回「None」),而不會引發「KeyError」或需要條件語句。

程式碼和執行輸出

此腳本示範了使用 in 運算子、 get() 後備方法驗證金鑰是否存在以及處理 KeyError 例外狀況。

check_dict_keys.py
在編輯器中嘗試
user = {"id": 101, "name": "Alice", "role": "admin"}

# 1. Checking key existence using the 'in' operator (Recommended)
if "role" in user:
    print("Found 'role' key. Value is:", user["role"])

if "email" not in user:
    print("'email' key is missing.")

# 2. Retrieving value safely using get() with a fallback
email_address = user.get("email", "no-email@example.com")
print("Email address:", email_address)

# 3. Handling KeyError exception manually
try:
    invalid_lookup = user["location"]
except KeyError:
    print("Caught KeyError: 'location' key does not exist.")
端子輸出
Found 'role' key. Value is: admin
'email' key is missing.
Email address: no-email@example.com
Caught KeyError: 'location' key does not exist.

逐步實施

  • 使用 in 運算子(例如,if key indictionary:)進行標準鍵存在檢查。
  • 使用 not in 運算子檢查字典結構中是否缺少某個鍵。
  • 呼叫dictionary.get(key, default_value) 可以安全地檢索值,同時提供預設回退。
  • 在第三方整合中處理遺失的按鍵時,將直接查找包裝在 try- except KeyError 區塊中。

常見問題解答

檢查字典中是否存在某個鍵的時間複雜度是多少?

平均時間複雜度為 O(1),因為字典在底層使用雜湊表,使得查找時間恆定,無論大小。

我可以檢查字典中是否存在某個值嗎?

是的,但您必須搜尋值視圖:if value in my_dict.values():。請注意,值檢查需要 O(N) 線性時間,因為 Python 必須遍歷字典中的每個元素。

相關主題

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。