codeforfun
codeforfun

Reputation: 187

How to assign a score to each sublist?

I have a dictionary and a list with sublists of separate words:

lst=[["love", "apple", "@"],["user", "hit", "hate"]]

dict{"love":3, "hate":-3}

I need to iterate through the sublists and evaluate if there is the word from the dictionary in the sublists and to assign a value to each sublist. The desired outcome is: 3 -3

I have tried the code below but it gives me the score of each word in the sublist. Where is my mistake?

def evaluation(list, dict):
    score=0
    for i in dict.keys():
        for sublst in list:
            if i in sublst:
                score+=dict.get(i)
            print(score)

Upvotes: 0

Views: 65

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Don't use variable names as list or dict, you are shadowing builtins. And you don't reset score value in each iteration to 0.

You can do this:

lst=[["love", "apple", "@"],["user", "hit", "hate"]]
d = {"love":3, "hate":-3}

score = [sum(d.get(val.lower(), 0) for val in sublst) for sublst in lst]

print(score)

To print:

[3, -3]

Upvotes: 2

Related Questions