简体   繁体   English

用空字典进行设置在Python中返回False

[英]Make a set with an empty dictionary return False in Python

If someone doesn't fill out any forms in my Django formset, it returns [{}] . 如果有人没有在我的Django表单集中填写任何表单,它将返回[{}]

How can I test whether this dictionary within a set has been populated or not? 如何测试集合中的该词典是否已填充? Something like the following, though this doesn't work as the empty dictionary seems to make the list return True: 如下所示,但由于空字典似乎使列表返回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"

In Python an empty dictionary or an empty list are "false", but a list containing and empty dictionary is instead "true". 在Python中,空字典或空列表为“ false”,而包含空字典的列表则为“ true”。

To do the check that you want therefore you need to enter the list and check the element: 因此,要进行所需的检查,您需要输入列表并检查元素:

 if form and form[0]:
    ...

this will enter the if body only if the list has at least one dictionary and the first dictionary is not empty 仅当列表中至少有一个词典并且第一个词典不为空时,才输入if正文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM