【问题标题】:Make a set with an empty dictionary return False in Python用空字典创建一个集合在 Python 中返回 False
【发布时间】:2014-03-14 06:50:00
【问题描述】:

如果有人没有在我的 Django 表单集中填写任何表单,它会返回 [{}]

如何测试集合中的这本字典是否已被填充?类似于以下内容,尽管这不起作用,因为空字典似乎使列表返回 True:

form_output_when_empty = [{}]
if form_output_when_empty:
    print "This should not print"
    # currently this prints out, which is not what I want!
else:
    print "This should print."

form_output_when_filled = [{'name': 'John'}]
if form_output_when_filled:
    print "This should print"
else:
    print "This should not print"

【问题讨论】:

    标签: python django dictionary


    【解决方案1】:

    在 Python 中,空字典或空列表为“假”,但包含空字典的列表为“真”。

    要进行所需的检查,因此您需要输入列表并检查元素:

     if form and form[0]:
        ...
    

    仅当列表至少有一个字典且第一个字典不为空时,才会进入if 正文

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 1970-01-01
      • 2018-04-30
      • 2017-07-14
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2012-01-15
      • 1970-01-01
      相关资源
      最近更新 更多