warrior4223 warrior4223 - 10 months ago 45
Python Question

Counting two values together in dictionary

I'm working on a function where I need to count how many times the combination of a country name and type of artwork appear together in the values of a dictionary and return the total count. I think I'm close but I'm having issues.

Example Dictionary:

{'V':[("Self-Portrait",1500,20.0,30.0,"oil paint","Italy")],
'B':[("Self-Portrait",1500,20.0,20.0,"oil paint","Italy")],
'K':[("Self-Portrait-1",1500,10.0,20.0,"oil paint","Netherlands"),("Self-Portrait-2",1510,10.0,20.0,"oil paint","Netherlands"),("Self-Portrait-3",1505,10.0,20.0,"oil paint","USA")],
'M':[("Self-Portrait-1",1800,20.0,15.0,"oil paint","USA"),("Self-Portrait-2",1801,10.0,30.0,"oil paint","France")]

In the above dictionary if I was counting for the number of times "oil paint" and "Italy appeared together in values it would return

count_appearances(dictionary4(),'oil paint','Italy')

#This should return "2"

This is the code I have so far. It is currently returning None for count and I'm not sure why

def count_media_in_country(db, media, country):
count = 0
for key in db:
for record in db[key]:
if media and country == True:
count += 1
elif media and country == False:
count += 0
return count

Answer Source

That is what you need:

def count_media_in_country(db, media, country):
    count = 0
    for value in db.values():
        for record in value:
            if record[4] == media and record[5] == country:
                count += 1
    return count # return statement should be after for loop (in this case)

if media and country == True: actually checks if media and country strings are not None and are not empty (you don't need that).

count += 0 does not do anything (obviously)

if statement == True:
    # something
elif statement == False:
    # something

better way to write this is:

if statement:
    # something
    # something