Bahar lila
Bahar lila

Reputation: 35

counting values in a dictionary Python3

a = {bob:home, amy:school, george:school, Noah:school, Lilian:home}

i'm trying to get this output:

number of people staying home is 2

number of people going to school is 3

please help

def counting(x):
  homecount: 0
  schoolcount: 0
for i in x.key:
   if i == home:
    homecount += 1
   else:
    schoolcount +=1
print (f' number of people staying home is {homecount} ')
print(f' number of people going to school is {schoolcount}')

Upvotes: 0

Views: 99

Answers (3)

JonSG
JonSG

Reputation: 13232

The other answers a perfectly fine, but you might also want to check out collections.Counter as it does a lot of the work for you in situations like this:

import collections

data = {"bob":"home", "amy":"school", "george":"school", "Noah":"school", "Lilian":"home"}
the_count = collections.Counter(data.values())

print(f'staying home: { the_count.get("home") }')
print(f'going to school: { the_count.get("school") }')

Gives you:

staying home: 2
going to school: 3

Upvotes: 0

gold_cy
gold_cy

Reputation: 14236

There are several problems with your code, including that some of the syntax is not valid Python.

def counting(x):
    homecount = 0
    schoolcount = 0
    for val in x.values():
        if val == "home":
            homecount += 1
        elif val == "school":
            schoolcount += 1
        else:
            continue
    print(f"The number of people staying home is {homecount}")
    print(f"The number of people going to school is {schoolcount}")

counting(a)
The number of people staying home is 2
The number of people going to school is 3
  1. To declare a variable use = not :.
  2. You want to iterate over values not keys.
  3. When comparing equality of values in your case, you have to use a "home" as a string, not a literal variable.
  4. Don't use else in this case without an elif because you can get wrong counts if the dictionary has values besides home and school.

Upvotes: 2

Cresht
Cresht

Reputation: 1040

the answer could be expressed using a sum.

i.e.

home_sum = sum([x=="home" for x in a.values()])
school_sum = sum([x=="school" for x in a.values()])

Upvotes: 1

Related Questions