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"))
However, all the dictionary doesn't contain the key Sepal_Length
, I am getting :
但是,所有字典都不包含密钥Sepal_Length,我得到:
KeyError: 'Sepal_Length'
How can i solve this?
我怎么解决这个问题?
1 个解决方案
#1
7
You can use dict.get
to get the value:
您可以使用dict.get来获取值:
next((item for item in data if item.get("Sepal_Length") == "7.9"))
dict.get
is like dict.__getitem__
except that it returns None
(or some other default value if provided) if the key is not present.
dict.get就像dict .__ getitem__,除非它返回None(如果提供了其他默认值),如果该键不存在。
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)
#1
7
You can use dict.get
to get the value:
您可以使用dict.get来获取值:
next((item for item in data if item.get("Sepal_Length") == "7.9"))
dict.get
is like dict.__getitem__
except that it returns None
(or some other default value if provided) if the key is not present.
dict.get就像dict .__ getitem__,除非它返回None(如果提供了其他默认值),如果该键不存在。
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)