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

Cli*_*ley 3 python dictionary python-3.5

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

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}]
Run Code Online (Sandbox Code Playgroud)

为了获得基于键和值的列表,我使用以下内容:

next((item for item in data if item["Sepal_Length"] == "7.9"))
Run Code Online (Sandbox Code Playgroud)

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

KeyError: 'Sepal_Length'
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

mgi*_*son 7

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

next((item for item in data if item.get("Sepal_Length") == "7.9"))
Run Code Online (Sandbox Code Playgroud)

dict.getdict.__getitem__不同之处在于它返回None(或如果提供了一些其他的默认值),如果该键不存在.


作为奖励,你实际上并不需要围绕生成器表达式的额外括号:

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

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

next((item for item in data if item.get("Sepal_Length") == "7.9"), default)
Run Code Online (Sandbox Code Playgroud)