我有一个字典数组,我想检查特定的键是否在字典数组中并检索该项目。 我知道如何使用列表理解来做到这一点,但是有没有办法在不这样做的情况下避免索引错误?
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]
我宁愿这样做:
result = [x[fruit]["weight"] for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}] if fruit in x.keys()][0]
但这有indexError的风险。
我可以用类似于 dict .get() 方法的数组做一些事情吗?所以我可以用一行干净的代码来编写它。
我仍然认为它很难看且难以阅读,但如果你真的必须,请使用
fruit = 'unknown'
result = [x[fruit]["weight"] if fruit in x.keys() else None for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}]][0]
请记住,我更改了
if fruit in x.keys()
的顺序并添加了 else None
您可以使用
next()
默认值:
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)
打印:
[]