I am trying to count the number of people who's status is Online. I hate created a dictionary and also have created a count variable to keep track of people who are online. Below is my code and the error log. In below code, I expect count to be 2.
class Solution(object):
def getStatus(self, status):
count = 0
for k, v in status.items():
# I even tried to used json.load(status) to parse but it doesn't help
if status[k].key() == "Online":
count = 1
else:
pass
return count
if __name__ == "__main__":
statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",
}
print(Solution().getStatus(statuses))
Below is my error log
if status[k].key() == "Online":
AttributeError: 'str' object has no attribute 'key'
CodePudding user response:
you want to check the value , you have access to it using variable v
you can use
if v == "online":
instead of
if status[k].key() == "Online":
why are you getting the error ?
status[k]
is the string which is the value in the dict, so you can't call function key()
on it. To verify this, just print status[k]
in your loop to observe this.
CodePudding user response:
In your loop, k
will Alice, Bob, etc and v
will be "online" or "offline". There's no key()
function to be called.
So for example:
if v == 'online':
....
That would work. Note that the evaluation is case-sensitive, and your example has mixed case, so that needs to be consistent.
Having said that, what you should use is operator.countOf, which is much simpler:
>>> statuses = {
... "Alice": "online",
... "Bob": "offline",
... "Eve": "online",
... }
>>> from operator import countOf
>>> countOf(statuses.values(), 'online')
2
>>> countOf(statuses.values(), 'offline')
1