Online status
The aim of this challenge is, given a dictionary of people’s online status, to count the number of people who are online.
For example, consider the following dictionary:
statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",
}
In this case, the number of people online is 2
.
Write a function named online_count
that takes one parameter. The parameter is a dictionary that maps from strings of names to the string "online"
or "offline"
, as seen above.
Your function should return the number of people who are online.
Â
==== SOLUTION ====
You can implement the `online_count` function in Python by iterating through the dictionary values and counting the occurrences of the string “online”. Here’s how you can do it:
“`python
def online_count(statuses):
      return list(statuses.values()).count(“online”)
# Test the function
statuses = {
    “Alice”: “online”,
   “Bob”: “offline”,
   “Eve”: “online”,
}
print(online_count(statuses)) # Output: 2
“`
Explanation:
1. `def online_count(statuses):`: This line defines a function named `online_count` that takes one parameter, `statuses`, which is a dictionary mapping names to online statuses.
2. `list(statuses.values())`: This part converts the values of the dictionary into a list. `statuses.values()` returns a view object containing the values of the dictionary, and `list()` converts it into a list so that we can use the `count()` method.
3. `.count(“online”)`: This part counts the number of occurrences of the string “online” in the list obtained from the dictionary values.
4. The function returns the count of people who are online.
So, when you call `online_count(statuses)` with the provided dictionary `statuses`, it will return the number of people who are online, which is 2.