finding a specific value from list of dictionary in python

ε祈祈猫儿з 提交于 2020-01-13 18:17:30

问题


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 :

KeyError: 'Sepal_Length'

How can i solve this?


回答1:


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 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)


来源:https://stackoverflow.com/questions/35446421/finding-a-specific-value-from-list-of-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!