从python中的字典列表中找到一个特定的值 [英] finding a specific value from list of dictionary in python
问题描述
我的字典列表中有以下数据:
I have the following data in my list of dictionary:
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}]
要获得一个基于键和值的列表,我使用以下内容:
And to get a list based upon a key and value I am using the following:
next((item for item in data if item["Sepal_Length"] == "7.9"))
但是,所有的字典都不包含密钥 Sepal_Length
,我得到:
However, all the dictionary doesn't contain the key Sepal_Length
, I am getting :
KeyError: 'Sepal_Length'
我解决了这个问题?
推荐答案
你可以使用 dict.get
获取值:
next((item for item in data if item.get("Sepal_Length") == "7.9"))
dict。得到
就像 dict .__ getitem __
,除了它返回无
(或其他一些默认值如果提供的话)如果钥匙不存在。
dict.get
is like dict.__getitem__
except that it returns None
(or some other default value if provided) if the key is not present.
作为一个奖励,你实际上不需要额外的括号在生成器表达式附近:
Just as a bonus, you don't actually need the extra parenthesis here around the generator expression:
# Look mom, no extra parenthesis! :-)
next(item for item in data if item.get("Sepal_Length") == "7.9")
,但如果您想指定一个默认值,它们会帮助您:
but they help if you want to specify a default:
next((item for item in data if item.get("Sepal_Length") == "7.9"), default)
这篇关于从python中的字典列表中找到一个特定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!