检查字典是否为空但有键

Ali*_*dra 1 python dictionary is-empty

我有一本字典,可能只有这些键。但可以有 2 个键,例如'news'and'coupon'或 only 'coupon'。如何检查字典是否为空?(下面的词典是空的。)

{'news': [], 'ad': [], 'coupon': []}
{'news': [], 'coupon': []}
Run Code Online (Sandbox Code Playgroud)

我写了代码,但它应该只需要 3 个键:

if data["news"] == [] and data["ad"] == [] and data["coupon"] == []:
    print('empty')
Run Code Online (Sandbox Code Playgroud)

怎样才能不只带3把钥匙?

Mar*_*ers 6

你的字典不是空的,只有你的价值观是空的。

使用以下any函数测试每个值:

if not any(data.values()):
    # all values are empty, or there are no keys
Run Code Online (Sandbox Code Playgroud)

这是最有效的方法;一旦遇到非空值就any()返回:True

>>> data = {'news': [], 'ad': [], 'coupon': []}
>>> not any(data.values())
True
>>> data["news"].append("No longer empty")
>>> not any(data.values())
False
Run Code Online (Sandbox Code Playgroud)

这里,非空意味着:该值具有布尔真值,True。如果您的值是其他容器(集、字典、元组),而且也适用于遵循正常真值约定的任何其他 Python 对象,它也可以工作。

如果字典为空(没有键),则无需执行任何不同的操作:

>>> not any({})
True
Run Code Online (Sandbox Code Playgroud)