I have an array of dictionaries and I want to check if a particular key is in the array of dicts and retrieve the item. I know how to do this using list comprehension but is there a way to avoid indexError without doing this?
result = [x[fruit]["weight"] for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}] if fruit in x.keys()]
if result:
weight_of_fruit = result[0]
I'd rather do this:
result = [x[fruit]["weight"] for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}] if fruit in x.keys()][0]
But this has a risk of indexError.
Is there something I can do with an array that is like a dict .get() method? So I can write this in a clean line of code.
You can use next()
with default value:
lst = [{"apple": {"weight": 0.25}}, {"orange": {"weight": 0.25}}]
fruit = "pear"
result = next((d[fruit]["weight"] for d in lst if fruit in d), [])
print(result)
Prints:
[]