daiqiangbudainiu
V2EX  ›  Python

判断 Dict 是否是空,我这样写是不对的吗?

By daiqiangbudainiu at 2019 年 2 月 21 日 · 5388 次点击

如 debug 的截图

QQ20190221-182258.png

link_and_name 这个是一个 dict,可以看到他目前是空 {} 但是我的代码中

if not link_and_name:
    return item

并不管用,还是没有 return

请问这是怎么回事


抱歉抱歉,我看到了,类型不是 Dict,是我代码逻辑的错误,打扰了

11 条回复  •  2019-02-28 15:39:18 +08:00
shm7
   1
shm7  
   2019 年 2 月 21 日 via iPhone
看看 stdlib 文档,对这些 collection bool value False 是指 len=0
zhouyang1203
   2
zhouyang1203  
   2019 年 2 月 21 日 via Android   ❤️ 2
楼主看样子是在爬不得了的东西
find456789
   3
find456789  
   2019 年 2 月 21 日   ❤️ 1
你的判断方法是正确的, 至于为何不如预期



你 type (link_and_name) 就明白了

点赞啊
longbye0
   4
longbye0  
   2019 年 2 月 21 日 via Android
RBQ。RBQ。
mayorbryant
   5
mayorbryant  
   2019 年 2 月 21 日
{str}'{}', 你所谓的是个字典其实是个字符串'{}',这个字符串非空,所以 not link_and_name is False
另外 elif os.path.exists('info') is False: 可以直接写成 elif not os.path.exists('info'):
baiye23333
   6
baiye23333  
   2019 年 2 月 21 日
判断一个 `dict` 是否为空,应该用 `len(dict.keys())==0`,你这样是判断是否为 `None`,判断是否在 dict 中,是 if key in dict.
weyou
   7
weyou  
   2019 年 2 月 21 日 via Android
@baiye23333 刚从别的语言转过来吧
iccfish
   8
iccfish  
   2019 年 2 月 21 日   ❤️ 2
New91Crawler ……(#`O ′)妖妖灵吗,这里有人蛇黄
yake1015
   9
yake1015  
   2019 年 2 月 22 日
你那是个字符串,不是字典
tcpdump
   10
tcpdump  
   2019 年 2 月 22 日
不得了, 爬 91
wwg1994
   11
wwg1994  
   2019 年 2 月 28 日
等等 你在爬 91 ?
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 47ms · 3.9.8.5