I am trying to create a function to count each time the string 'online' appears as a value in a dictionary.
For example, inputting the following dictionary into the function should yield 2, but I only get 0.
statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",}
The following is what I've come up with so far. This function only returns 0. How could I get the function to return the correct count? Why is it returning 0?
def online_count(dict_a):
count = 0
for i in dict_a:
if dict_a[i] == "online":
count 1
return count
CodePudding user response:
Your solution is on the right track! You have the right idea in terms of increasing the counter if the value at the current index of the loop is equal to "online"
however you are not actually increasing the count
, you are just adding to it though that expression is not actually saved to the variable.
count 1
should be:
count = count 1
The reason for this is so that you can make count
equal to itself (its current counter value), and 1 to increase the counter.
To simplify this further, you can just write count = 1
which does the same thing.
Final Code:
statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online"
}
def online_count(dict_a):
count = 0
for i in dict_a:
if dict_a[i] == "online":
count = 1
return count
CodePudding user response:
The loop isn't incrementing count
- it's adding it and 1, and ignoring the result. You could use =
to do that:
count = 1
CodePudding user response:
You need to make sure the lines in the function are properly indented first.
Then you use
count 1
which will give the count value plus 1 to nothing.
You need to reassign to count with
count = count 1
or it’s short version
count = 1
CodePudding user response:
Other answers indicated the problem in your code is that you're not assigning the new value to count
. Here is an alternate method using the collections.Counter
container.
>>> from collections import Counter
>>> counts = Counter(statuses.values())
>>> counts
Counter({'online': 2, 'offline': 1})
>> counts['online']
2
CodePudding user response:
if there are other value and you ever want to put in dictionary.
import collections
statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",
"Adam" : "1mn rest"
}
a = statuses.values()
counter= collections.Counter(a)
print(counter)