Home > Blockchain >  How to create a for loop in python to access the key values of a dictionary using the characters of
How to create a for loop in python to access the key values of a dictionary using the characters of

Time:11-16

So, I have a dictionary of the entire alphabet with the characters as its keys and different numbers between 1-9 as its values.

SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j':
8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't'
: 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}

What I would like to know is how to, given a word, find the sum of the corresponding key values associated with the keys ie. the characters in the word.

eg

abc

would yield 7.

I have written the following code

def get_word_score(word,n):
    """Assumes the word is correct and calculates the score, will need to handle strings with mixed cases"""
    sum = 0
    word_low = word.lower()
    for i in word_low:
        sum  = LETTER_VALUES[i]
    return sum

Any help would be greatly appreciated :)

CodePudding user response:

It seems that you are calling the wrong dictionary: should it be SCRABBLE_LETTER_VALUES (assuming it's defined globally above). Secondly, not sure what's the role of n in your function signature? Because it's never been used?!

Alternatively, you can simplify the processing to just use generator expression and passing to sum in one shot:

Be reminded - in Python, a string (word) is also an interable that you can iterate.

LETTER_VALUES is your orig. dictionary.

def get_word_score(word):
    return sum(LETTER_VALUES[ch] for ch in word.lower())
    

In [4]: get_word_score("ABBA")
Out[4]: 8

In [5]: get_word_score("Dr")
Out[5]: 3

In [6]: get_word_score('Zoo')
Out[6]: 12

CodePudding user response:

Your code is almost correct. I just modified your code a little bit, so that you can understand how your code can be improved, as follows:

  1. It seems that the functin 'get_word_score' does not need parameter 'n', so I removed it.
  2. In get_word_score function, I changed 'LETTER_VALUES' to 'SCRABBLE_LETTER_VALUES'.
  3. I changed variable name sum to 'sum_of_val' bacause sum is a built-in function as @daniel-hao commented
def get_word_score(word):
    """Assumes the word is correct and calculates the score, will need to handle strings with mixed cases"""
    sum_of_val = 0
    word_low = word.lower()
    for i in word_low:
        sum_of_val  = SCRABBLE_LETTER_VALUES[i]
    return sum_of_val

SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j':
8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't'
: 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}

result = get_word_score('abc')
print(result)

# 7
  • Related