简体   繁体   中英

Python: check for a KeyError in a list comprehension?

有没有办法,如果mydict没有entries ,我可以在一行中编写以下内容而不会导致mydict

b = [i for i in mydict['entries'] if mydict['entries']]

You can use dict.get() to default to an empty list if the key is missing:

b = [i for i in mydict.get('entries', [])]

In your version, the if filter only applies to each iteration as if you nested an if statement under the for loop:

for i in mydict['entries']:
    if mydict['entries']:

which isn't much use if entries throws a KeyError .

你可以试试这段代码:

b = [i for i in mydict.get('entries', [])]

你想要的东西:

b = [i for i in mydict.get('entries', [])]

there is another way to do this, Dict.setdefault .

>>> d = {}
>>> import time
>>> time.ctime(
... )
'Thu May  1 18:11:53 2014'
>>> d = {}
>>> a = d.setdefault('time',time.ctime())
>>> a
'Thu May  1 18:12:17 2014'
>>> d
{'time': 'Thu May  1 18:12:17 2014'}
>>>  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM