Jimmy Coltrane
Jimmy Coltrane

Reputation: 45

Counting a specific word in a dictionary

I'm trying to count the number of people 'online', given in the statuses dictionary. This is the code I have but it is outputting 0.

def online_count(statuses):
    count = 0
    for x in statuses.items():
       if x =='online': 
          count += 1
    return count

statuses = {
    "Alice": "online",
    "Bob": "offline",
    "Eve": "online",
}

print(online_count(statuses))

Upvotes: 1

Views: 75

Answers (2)

Jab
Jab

Reputation: 27485

Your return is indented too far. Move it outside the loop. That said you can use sum and a comprehension for this:

def online_count(statuses):
    return sum(s == 'online' for s in statuses.values())

Thanks @Sayandip Dutta!

Upvotes: 2

The Pilot Dude
The Pilot Dude

Reputation: 2237

Try this:

statuses = { "Alice": "online", "Bob": "offline", "Eve": "online", }

def online_count(statuses):
    lst = list(statuses.values())
    return lst.count("online")

print(online_count(statuses))

Basically, first it gets a list of all the values in the dictionary. In case you don't know, dictionaries are used to store data values in key:value pairs. Therefore, a list of all the values would mean a list of all the "online" / "offlines"

Upvotes: 2

Related Questions