【问题标题】:How to check if a List contains empty dictionary or not如何检查列表是否包含空字典
【发布时间】:2020-06-24 16:56:46
【问题描述】:

假设我有这两个字典:

empty_retr = {'info': [], 'return': [{}]}
non_empty_retr = {'info': [], 'return': [{'some_host': True, 'some_more_host': True, 'Blah': True}]}

我想检查 empty_retr['return'] 是否是一个包含一些带有数据的字典的列表。我们如何才能以简单和维护 Python 的方式做到这一点?

【问题讨论】:

  • empty_retr['return'] == [{}]?
  • 您能否提供更多上下文 - 您尝试了什么?有什么限制 - 例如,'return' 的值是否总是一个项目的列表?

标签: python list python-2.7 dictionary


【解决方案1】:
if empty_retr['return']== [{}]:
   do something

【讨论】:

  • 如果你做一个 len([{}]) 它仍然会返回 1,所以我觉得这将是最明智的。
【解决方案2】:

如果你想检查它的字典是否包含东西,你必须检查它是否是字典:

if isinstance(empty_retr['return'][0], dict):
    # do something

编辑:

如果它应该是一个包含可以为空的字典的列表:

if isinstance(empty_retr['return'], list) 
        and isinstance(empty_retr['return'][0], dict):
    # do something

【讨论】:

    【解决方案3】:

    一种方法是:

    if not empty_retr['return'][0]:
        # do something with the empty dict
    

    这也有效:

    if not bool(empty_retr['return'][0]):
        # do something with the empty dict
    

    【讨论】:

    • not bool(...) 似乎是多余的 - 请参阅 docs.python.org/3/library/stdtypes.html#truth-value-testing
    • 问题是它是否是一个包含字典的列表。这可以是除 None0False 之外的任何内容...
    • @BramDekker 这是不正确的,因为字典在这两种情况下都存在。我很好奇如何检查字典是否为空
    • @ReconAlpha 我的答案检查字典是否为空。一般来说,如果你有一个字典 dnot d 如果 d 为空则返回 True,如果 d 不为空则返回 False
    猜你喜欢
    • 2021-05-18
    • 2020-05-09
    • 2020-07-10
    • 2016-05-12
    • 1970-01-01
    • 2017-02-27
    • 2018-07-24
    • 2019-11-02
    • 2017-02-10
    相关资源
    最近更新 更多