【问题标题】:Check if dictionary is empty but with keys检查字典是否为空但有键
【发布时间】:2022-07-21 10:52:07
【问题描述】:

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

{'news': [], 'ad': [], 'coupon': []}
{'news': [], 'coupon': []}

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

if data["news"] == [] and data["ad"] == [] and data["coupon"] == []:
    print('empty')

如何不只取3把钥匙?

【问题讨论】:

    标签: python dictionary is-empty


    【解决方案1】:

    你的字典不是空的,只有你的是。

    使用any function:测试每个值:

    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
    

    这里,不为空的意思是:值有boolean truth value,即True。如果您的值是其他容器(集合、字典、元组),但也适用于任何其他遵循正常真值约定的 Python 对象,它也可以工作。

    如果字典为空(没有键),则无需做任何不同的事情:

    >>> not any({})
    True
    

    【讨论】:

      【解决方案2】:

      如果它不是空的,但它的所有值都是假的:

      if data and not any(data.values()):
          print(empty)
      

      【讨论】:

        【解决方案3】:

        并排比较以更好地帮助理解 any() 函数并检查空值。

        # sample code
        val_1 = {'news': [], 'ad': [], 'coupon': []}
        print(val_1)
        print(any(val_1.values()))
        
        val_2 = {'news': [1, 2], 'ad': [], 'coupon': []}
        print(val_2)
        print(any(val_2.values()))
        
        
        # prints out
        {'news': [], 'ad': [], 'coupon': []}
        False
        {'news': [1, 2], 'ad': [], 'coupon': []}
        True
        

        【讨论】:

          猜你喜欢
          • 2020-06-10
          • 2014-09-14
          • 1970-01-01
          • 1970-01-01
          • 2013-01-04
          • 1970-01-01
          • 2013-11-16
          • 2013-11-23
          • 2014-08-17
          相关资源
          最近更新 更多