从 python 中的字典列表中查找特定值

finding a specific value from list of dictionary in python

我的字典列表中有以下数据:

data = [{'I-versicolor': 0, 'Sepal_Length': '7.9', 'I-setosa': 0, 'I-virginica': 1},
{'I-versicolor': 0, 'I-setosa': 1, 'I-virginica': 0, 'Sepal_Width': '4.2'},
{'I-versicolor': 2, 'Petal_Length': '3.5', 'I-setosa': 0, 'I-virginica': 0},
{'I-versicolor': 1.2, 'Petal_Width': '1.2', 'I-setosa': 0, 'I-virginica': 0}]

要根据键和值获取列表,我使用以下内容:

next((item for item in data if item["Sepal_Length"] == "7.9"))

但是,所有字典都不包含键 Sepal_Length,我得到:

KeyError: 'Sepal_Length'

我该如何解决这个问题?

您可以使用dict.get获取值:

next((item for item in data if item.get("Sepal_Length") == "7.9"))

dict.get 类似于 dict.__getitem__ 除了它 returns None (或其他一些默认值,如果提供)如果密钥不存在。


作为奖励,您实际上不需要在生成器表达式周围加上额外的括号:

# Look mom, no extra parenthesis!  :-)
next(item for item in data if item.get("Sepal_Length") == "7.9")

但如果您想指定默认值,它们会有所帮助:

next((item for item in data if item.get("Sepal_Length") == "7.9"), default)