如果有人没有填写我的 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中,空字典或空列表是“假”,但包含空字典的列表是“真”。
要进行所需的检查,因此您需要输入列表并检查元素:
if form and form[0]:
...
仅当列表至少有一个字典并且第一个字典不为空时,才会进入 if
主体
关于python - 在 Python 中使用空字典创建一个集合返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22398017/