Chris
Chris

Reputation: 89

Returning dict Value with a variable Key

I am using the characters in a word to search the keys of a dictionary. The dictionary is SCRABBLE_LETTER_VALUES: { 'a' : 1, 'b' : 3, ...} and so on.

Here is my incomplete code:

"""  
Just a test example
word = 'pie'
n = 3
"""

def get_word_score(word, n):
"""
Returns the score for a word. Assumes the word is a
valid word.

The score for a word is the sum of the points for letters
in the word multiplied by the length of the word, plus 50
points if all n letters are used on the first go.

Letters are scored as in Scrabble; A is worth 1, B is
worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.

word: string (lowercase letters)
returns: int >= 0
"""
 score = 0
 for c in word:
   if SCRABBLE_LETTER_VALUES.has_key(c):
     score += SCRABBLE_LETTER_VALUES.get("""value""")

Now this code is incomplete because I'm still learning python, so I'm still thinking through this problem, but I am stuck on the aspect of returning a value with a key that changes each iteration.

My though was maybe I could set c equal to the key it matches and then return the value, but I'm not sure how to do that. Also, I wanted to check to see if I am indeed on the right thought process, so to speak.

Just FYI this code base does enter the loop successfully, I am simply not able to retrieve the value.

Thanks for the advice!

Upvotes: 1

Views: 715

Answers (2)

rocambille
rocambille

Reputation: 15976

You can do the following:

score = 0
for c in word:
    score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score

get() will return the value of the key if the dictionary contains it, otherwise it will return the default value passed as second argument (0 in the snippet).

Upvotes: 2

Doron Cohen
Doron Cohen

Reputation: 1046

You put zero in score in every iteration. You should initialize it before the for loop.

score = 0
for c in word:
    score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score

Upvotes: -1

Related Questions