As other answers mentioned you can not use an try-except inside a list comprehension. But as a tricky approach you can use collections.defaultdict() and override the __missing__ attribute in order to catch the exceptions. Here is an example:
from collections import defaultdict
class Mydefaultdict(defaultdict):
def __init__(self, *args, **kwargs):
super(Mydefaultdict, self).__init__(*args, **kwargs)
def __getitem__(self, key):
try:
return defaultdict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
# Instead of printing you can catch your exceptions in any way you like
print("{} doesn't exist".format(key))
if self.default_factory:
return self.default_factory() # You can rturn whatever you want here
Demo:
d = Mydefaultdict(None, {4: 'b', 1: 'a'})
print([d[i] for i in [1, 2]])
2 doesn't exist
['a', None]