[英]Checking for key and value in python dictionary
在進一步處理之前,我需要檢查 Python 字典中是否存在鍵,並且多個鍵的值不是空/空。
exception = False
if 'key1' in d and d['key1']:
pass
else:
exception = True
if 'key2' in d and d['key2']:
pass
else:
exception = True
if 'key3' in d and d['key3']:
pass
else:
exception = True
if not exception:
#Process it
我覺得這段代碼非常丑陋,也不是 Pythonic。
我們可以更好地編寫邏輯嗎?
您可以使用all
和生成器:
if all(k in d and d[k] for k in ['key1', 'key2', 'key3']):
pass
else:
exception = True
您實際上可以跳過使用標志:
if not all(k in d and d[k] for k in ['key1', 'key2', 'key3']):
# process
或者
if any(k not in d or not d[k] for k in ['key1', 'key2', 'key3']):
# process
您可以使用d.get(k)
:
if all( d.get(k) for k in ["key1","key2","key3"]):
exception = False
else:
exception = True
或者
exception = all( d.get(k) for k in ["key1","key2","key3"])
您可以將try/except
與operator.itemgetter
一起使用,或使用dict.get
:
from operator import itemgetter
try:
exception = not all(itemgetter('key1', 'key2', 'key3')(d))
except KeyError:
exception = True
或者,
exception = not all(map(d.get, ('key1', 'key2', 'key3')))
這應該給你正確的布爾值。
exception = False
for k in ['key1', 'key2', 'key3']:
if k in d and d[k]:
exception = True
break
@mozway 的答案更 Pythonic 和更好,但無論如何這里是使用 function 的另一種方法。
def check_dict(dictionary):
for key, value in dictionary.items():
if key not in ("key1", "key2", "key3"):
return False
return True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.