在字典中一起计算两个值

Counting two values together in dictionary

我正在开发一个函数,我需要计算国家名称和艺术品类型的组合在字典值中出现的次数以及 return 总计数。我想我已经接近了,但我遇到了问题。

示例词典:

{'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")]
        }

在上面的字典中,如果我计算 "oil paint" 和“意大利一起出现在值中的次数,它会 return

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

#This should return "2"

这是我目前的代码。目前正在 returning None 进行计数,我不确定为什么

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

这就是你需要的:

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: 实际上检查 mediacountry 字符串是否不是 None 并且不为空(您不需要那个)。

count += 0 什么都不做(显然)

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

更好的写法是:

if statement:
    # something
else:
    # something
def count_media_in_country(db, media, country): 
    count = 0
    for key in db:
        for record in db[key]:
            if media in record and country in record:
                count += 1
    return count

您的 elif 块提前返回。此外,您必须使用 in 关键字分别检查每个项目的列表成员资格。