kg123
kg123

Reputation: 47

Python- how to compare values that change with each iteration of loop on dictionary?

Given a dictionary (db) and string (type), my function needs to search through the whole dictionary and find all items that have string(type) as their ONLY type, find all items that have type as 1/2 of their types, and sums the two values. Then it must return the tuple of the statistics.

I'm hung up on how to keep track of the counter and the function is returning incorrect tuples. I think my structure may be sound but I know it's not working properly. How can I fix this? What will help me keep track of the counter? Is my issue with the if statements not checking correctly?

Here is my current code:

def count_by_type(db,type):
    only_type=0
    half_type=0
    for key, values in db.item():
        if type in values[1] or values[2]:
            half_type+=1
        if type in (values[1] or values[2]) and (values[1] or values[2]==None:)
            only_type+=1
    my_sum=half_type+ only_type
    return (only_type, half_type, my_sum)

Here is an example of expected input/output:

db={'bulb':(1,'Grass','poison', 1, False), 
    'Char':(4, 'poison','none', 1, False)}

types='poison'

'char' has poison as its only type, only_type+=1
'bulb' has poison as 1/2 of its types, half_type +=1
my_sum=2
return: (1,1,2)

Upvotes: 0

Views: 1571

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49804

There were a few syntax issues in your code that were causing the logic to not evaluate as you expected. Here is corrected code.

Code:

def count_by_type(the_db, the_type):
    only_type = 0
    half_type = 0
    for values in the_db.values():
        if the_type in (values[1], values[2]):
            if None in (values[1], values[2]):
                only_type += 1
            else:
                half_type += 1

    return only_type, half_type, half_type + only_type

Test Code:

db = {
    'bulb': (1,'Grass', 'poison', 1, False),
    'Char': (4, 'poison', None, 1, False)
}

print(count_by_type(db, 'poison'))

Results:

(1, 1, 2)

Upvotes: 1

Related Questions