使用空字典创建一个集合,在Python中返回False

时间:2014-03-14 06:50:01

标签: python django dictionary

如果某人未在我的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"

1 个答案:

答案 0 :(得分:1)

在Python中,空字典或空列表为“false”,但包含空字典的列表则为“true”。

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

 if form and form[0]:
    ...

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