Frage

Is there a way that I can write the following in a single line without causing a KeyError if entries is not present in mydict?

b = [i for i in mydict['entries'] if mydict['entries']]
War es hilfreich?

Lösung

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.

Andere Tipps

You can try this code:

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

You want something like:

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'}
>>>  
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top