将字典中的键与字符串列表进行比较并对值进行求和

时间:2015-11-11 20:25:43

标签: python dictionary

所以我做了一个字典,键是单词,值是与每个单词相关的数值。我也有一个单词列表。我想取列表中的单词,看看它们中是否有任何字典。如果列表中的单词在词典中,我需要能够添加与每个单词相关联的值。

dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
list = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]

3 个答案:

答案 0 :(得分:2)

使用列表理解:

dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
lst = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]

print sum([dictionary[i] for i in lst if i in dictionary])

答案 1 :(得分:1)

如果密钥不存在,您可以使用get上的dict使用默认值返回。

此外,即使在一个示例中,字典和列表也不是好的变量名称:

>>> weights = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
>>> sentence = 'I am so happy this is the greatest day ever I am so excited !'

>>> sum(weights.get(word, 0) for word in sentence.split())
20

答案 2 :(得分:0)

不要将列表用作变量名称(它是关键字)

此代码可以满足您的需求:

sum_value = 0
for item in list1:
    if item in dictionary:
        sum_value += dictionary[item]