![](/img/trans.png)
[英]Python dict easiest and cleanest way to get value of key2 if key1 is not present
[英]Terse way of writing "if key1 or key2 are not in dict" Python
簡單的問題,只是想知道是否有比像這樣寫兩次更短的方法來檢查字典中的鍵:
if "bar" not in foo.keys() or "baz" not in foo.keys():
你不需要調用鍵
if "bar" not in foo or "baz" not in foo:
if "bar" not in foo.keys() or "baz" not in foo.keys():
是相同的:
if "bar" not in foo or "baz" not in foo:
是相同的:
if not ("bar" in foo and "baz" in foo):
是相同的:
if not all(key in foo for key in ("bar", "baz")):
是相同的:
if not {"bar", "baz"}.issubset(foo):
后者是我要使用的,尤其是當我有一堆值要測試時。
一種選擇是對any
或all
使用列表理解以及鍵列表來對字典中的鍵進行不同的檢查。 根據您實際想要檢查的邏輯,有多種方法可以使用這些方法進行檢查。
字典中缺少任何鍵
這就是您的示例代碼所做的。
等同於if "bar" not in foo or "baz" not in foo:
if any(k not in foo for k in ["bar", "baz"]):
# or
if not all(k in foo for k in ["bar", "baz"]):
字典中沒有任何鍵
等同於if "bar" not in foo and "baz" not in foo:
if not any(k in foo for k in ["bar", "baz"]):
所有的鍵都在字典中
相當於if "bar" in foo and "baz" in foo:
if all(k in foo for k in ["bar", "baz"]):
如果要檢查的鍵很多,可以把它拉出來放到一個單獨的列表中,並保持if語句的長度不變
key_list = ["bar","bax","baz","bor","bam"]
if all(k in foo for k in key_list):
假設foo
是一本字典,你不需要寫.keys()
。
"bar" in foo
可以工作並且更短。
使用any()
更簡潔但並不真正更短:
if any(x not in foo for x in ["bar", "baz"]):
如果您要檢查兩個以上的鍵, any()
肯定會更短。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.