Catching exceptions in a list comprehension

Viewed 30

I did a list comprehension with

result =[df_dict[letter] for letter in user_input]

this works aslong the letter is a key in df_dict. Now i tried to catch exceptions, but i cant figure out how i pass the latter if a Key Error occurs if I wanna use a list comprehension.

This is the solution i found so far.

result =[]
for letter in user_input:
    try:
        result.append(df_dict[letter])
    except KeyError:
        pass
1 Answers

You can not catch exception in comprehension, but for dictionary, you can use .get method passing the key, which won't raise any error if key doesn't exist.

>>> result =[df_dict.get(letter) for letter in user_input]

But above solution will create a list with None values if key doesn't exist in the dictionary so you'll have to first check if the key is in the dictionary or not:

>>> [df_dict[letter] for letter in user_input and letter in df_dict]

But if you are using Python 3.9+, you can also use named expression using :=, here is an example

>>> d={'a':5}
>>> [v for k in "abc" if k in 'abcd' and (v:=d.get(k)) is not None]
[5]
Related