我有一本字典,它可能只有這些鍵。但是可以有 2 個鍵,例如'news'and'coupon'或 only 'coupon'。如何檢查字典是否為空?(下面的字典是空的。)
{'news': [], 'ad': [], 'coupon': []}
{'news': [], 'coupon': []}
我撰寫了代碼,但它應該只需要 3 個鍵:
if data["news"] == [] and data["ad"] == [] and data["coupon"] == []:
print('empty')
如何不只取 3 把鑰匙?
uj5u.com熱心網友回復:
你的字典不是空的,只有你的值是。
any使用函式測驗每個值:
if not any(data.values()):
# all values are empty, or there are no keys
這是最有效的方法;一旦遇到一個非空值就any()回傳:True
>>> data = {'news': [], 'ad': [], 'coupon': []}
>>> not any(data.values())
True
>>> data["news"].append("No longer empty")
>>> not any(data.values())
False
在這里,非空意味著:該值具有布爾真值,即True。如果您的值是其他容器(集合、字典、元組),但也適用于任何其他遵循正常真值約定的 Python 物件,它也可以作業。
如果字典為空(沒有鍵),則無需做任何不同的事情:
>>> not any({})
True
uj5u.com熱心網友回復:
如果它不是空的,但它的所有值都是假的:
if data and not any(data.values()):
print(empty)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453491.html
