在字典中一起计算两个值

时间:2016-11-14 21:19:31

标签: python python-3.x dictionary counting

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

示例词典:

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

在上面的字典中,如果我计算的次数"油画"和#34;意大利一起出现在它将返回的价值中

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

#This should return "2"

这是我到目前为止的代码。它目前返回无计数,我不知道为什么

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

2 个答案:

答案 0 :(得分:1)

这就是你所需要的:

( ͡° ͜ʖ ͡°)

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:media字符串是否不是country且不为空(您不需要)。

None没有做任何事情(很明显)

count += 0

写这个的更好方法是:

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

答案 1 :(得分:0)

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关键字分别检查每个项目的列表成员资格。