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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With