=Start=
缘由:
整理、记录、备忘
正文:
参考解答:
- 从dict中取值时,一定要使用.get()方法,而不是数组的方式,避免KeyError异常;
- 在使用前判空 or 加上try..catch语句块预防异常;
In [50]: resp = {"total": 0, "rows": []} ...: alist = resp.get('rows') ...: In [51]: if not alist: ...: print 'hi' #当alist为空列表时会执行print ...: hi In [52]: if alist: ...: print 'hi' ...: In [53]: resp.get('rows') Out[53]: [] In [54]: resp.get('row') In [55]: print resp.get('row') None In [56]: print resp.get('row', '') In [57]:
&
In [60]: if len(resp['rows']) == 0: ...: print 'hi' ...: hi In [61]: if not resp.get('rows'): ...: print 'hi' ...: hi In [62]: if not resp['rows']: ...: print 'hi' ...: hi In [63]: if not resp['row']: ...: print 'hi' ...: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-63-94470f6bb953> in <module>() ----> 1 if not resp['row']: 2 print 'hi' KeyError: 'row' In [64]: if not resp.get('row'): ...: print 'hi' ...: hi In [65]:
参考链接:
- Most elegant way to check if the string is empty in Python?
- Python中的真值测试
- 如何检查一个字符串/变量是否为空?
- 如何检查一个list是否为空?
- Python中创建空列表的最快方法
=END=