python列表中的字典的相同value的个数,从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"))

However, all the dictionary doesn't contain the key Sepal_Length, I am getting :

KeyError: 'Sepal_Length'

How can i solve this?

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值