在Python中使用空字典生成集并返回False

2024-04-19 17:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如果有人没有在我的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"

Tags: djangoform表单outputif字典notthis
1条回答
网友
1楼 · 发布于 2024-04-19 17:29:28

在Python中,空字典或空列表是“false”,而包含空字典的列表则是“true”。你知道吗

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

 if form and form[0]:
    ...

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

相关问题 更多 >