python字典值的数量_Python 2.7计数具有给定值的字典项的数量

first question here, so i will get right to it:

using python 2.7

I have a dictionary of items, the keys are an x,y coordinate represented as a tuple: (x,y) and all the values are Boolean values.

I am trying to figure out a quick and clean method of getting a count of how many items have a given value. I do NOT need to know which keys have the given value, just how many.

there is a similar post here:

How many items in a dictionary share the same value in Python, however I do not need a dictionary returned, just an integer.

My first thought is to iterate over the items and test each one while keeping a count of each True value or something. I am just wondering, since I am still new to python and don't know all the libraries, if there is a better/faster/simpler way to do this.

thanks in advance.

解决方案

This first part is mostly for fun -- I probably wouldn't use it in my code.

sum(d.values())

will get the number of True values. (Of course, you can get the number of False values by len(d) - sum(d.values())).

Slightly more generally, you can do something like:

sum(1 for x in d.values() if some_condition(x))

In this case, if x works just fine in place of if some_condition(x) and is what most people would use in real-world code)

OF THE THREE SOLUTIONS I HAVE POSTED HERE, THE ABOVE IS THE MOST IDIOMATIC AND IS THE ONE I WOULD RECOMMEND

Finally, I suppose this could be written a little more cleverly:

sum( x == chosen_value for x in d.values() )

This is in the same vein as my first (fun) solution as it relies on the fact that True + True == 2. Clever isn't always better. I think most people would consider this version to be a little more obscure than the one above (and therefore worse).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值