檢查給定的多個鍵是否在Python字典中存在


在使用Python進行資料分析時,我們可能需要驗證幾個值是否作為鍵存在於字典中。以便分析的下一部分只能使用作為給定值一部分的鍵。在本文中,我們將看到如何實現這一點。

使用比較運算子

要檢查的值被放入一個集合中。然後將集合的內容與字典的鍵集合進行比較。>= 符號表示字典中的所有鍵都存在於給定的值集合中。

示例

 線上演示

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# Use comaprision
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")

輸出

執行以上程式碼將得到以下結果:

All keys are present
All keys are not present

全部存在

在這種方法中,我們使用for迴圈來檢查字典中是否存在每個值。只有當檢查鍵集中的所有值都存在於給定字典中時,all函式才返回true。

示例

 線上演示

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# Use all
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("All keys are not present")

輸出

執行以上程式碼將得到以下結果:

All keys are present
All keys are not present

使用子集

在這種方法中,我們將要搜尋的值作為一個集合,並驗證它是否是字典鍵的子集。為此,我們使用issubset函式。

示例

 線上演示

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys=set(["Tue","Thu"])

# Use all
if (check_keys.issubset(Adict.keys())):
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys=set(["Mon","Fri"])
if (check_keys.issubset(Adict.keys())):
   print("All keys are present")
else:
   print("All keys are not present")

輸出

執行以上程式碼將得到以下結果:

All keys are present
All keys are not present

更新於:2020年5月13日

2K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.