Is there a way to handle errors in a python list comprehension. Preferably I would have something like this where the last two values are represented by None
:
values = [try i ["row"] except KeyError None for i in [{"row" : 1}, {"Row" : 0}, {}]]
This throws a syntax error and the only way I can do it is:
values = [] for i in [{"row" : 1}, {"Row" : 0}, {}]: try: values.append (i ["row"]) except KeyError: values.append (None)
I hope there is a more ‘neat’ way of doing this because the current solution is not preferable due to having to append to a blank list when a list comprehension does this in such a nice way!
Advertisement
Answer
you cannot catch an exception from a list comprehension (How can I handle exceptions in a list comprehension in Python?). But given what you want to do you could use get
:
values = [i.get("row") for i in [{"row" : 1}, {"Row" : 0}, {}]]
if the key isn’t found in the dictionary get
returns None
, exactly what you’re looking for (it can return anything you want, just by passing the default value as second argument, see Why dict.get(key) instead of dict[key]?)