Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compact this for?

I have a dictionary of dictionaries. I want to count how many of those dictionaries has element "status" set to "connecting".

This is my working code:

connecting = 0
for x in self.servers:
    if self.servers[x]["status"] == "connecting": connecting += 1

Is there any way of compacting this? I was thinking something like:

connecting = [1 if self.servers[x]["status"] == "closed" else 0 for x in self.servers]

But it just returns a list of 0 and 1, doesn't add that 1 to connecting, which is what I expected.

like image 490
mesafria Avatar asked Jul 05 '26 12:07

mesafria


2 Answers

You can use a generator expression within sum function :

sum(x["status"]=="connecting" for x in self.servers.values()) 

Note that since the result of x["status"]=="connecting" is a boolean value and if it be True python will evaluated it as 1, so in the end it will returns the number of dictionaries that follows your conditions.

like image 66
Mazdak Avatar answered Jul 08 '26 00:07

Mazdak


You can use sum for this. You have the list comprehension already, so just wrap it in sum.

connecting = sum(1 for x in self.servers if self.servers[x]["status"] == "closed")
like image 41
Morgan Thrapp Avatar answered Jul 08 '26 01:07

Morgan Thrapp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!