[英]Comparing keys from dictionaries to a list of strings and summing the values
所以我做了一個字典,鍵是單詞,值是與每個單詞相關的數值。 我也有一個單詞列表。 我想取列表中的單詞,看看它們中是否有任何字典。 如果列表中的單詞在字典中,我需要能夠將與每個單詞相關聯的值相加。
dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
list = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]
使用列表理解:
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])
不要將列表用作變量名(它是關鍵字)
這段代碼可以滿足您的需求:
sum_value = 0
for item in list1:
if item in dictionary:
sum_value += dictionary[item]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.