Finding a specific value from a dictionary list in python

I have the following data in my 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 on key and value, I use the following:

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

However, the entire dictionary does not contain the Sepal_Length key, I get:

 KeyError: 'Sepal_Length' 

How can i solve this?

+1
python dictionary
Feb 17 '16 at 1:41
source share
1 answer

You can use dict.get to get the value:

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

dict.get is similar to dict.__getitem__ , except that it returns None (or another default value if provided) if the key is missing.




As a bonus, you really don't need an extra bracket 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 value:

 next((item for item in data if item.get("Sepal_Length") == "7.9"), default) 
+6
Feb 17 '16 at 1:43
source share



All Articles