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

标签 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"

最佳答案

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

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

 if form and form[0]:
    ...

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

关于python - 在 Python 中使用空字典创建一个集合返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22398017/

相关文章:

python - 获取 Django 中所有已安装应用程序及其属性的列表

python - 如何在python3中用无字符替换 `c2a0`?

Python:删除大数据

python - 下载Excel文件

python - pyyaml 3.11 将字典传递给迭代器?

c# - 无法使用字典反序列化 json 对象

python - 从 psycopg2 获取字典

python - Scikit Learn - 如何绘制概率

python - 解析 **kwargs

python - Django 管理员 : __str__ returned non-string (type long) on adding a user