Chris Schell Chris Schell - 3 months ago 21
Python Question

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!

Answer

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).