How can I access a dictionary key value inside of a loop?

No secret, it’s the nature of a dictionary which is nothing more than a look-up table. Give a key, get a value.

>>> score['q']

Hey everyone. I struggled with this problem a bit, but after realizing that we can use nested for loops, I got something that works. Here is the code:

def scrabble_score(word):
  total = 0

  for char in word:
    for key in score:
      if char.lower() == key:
        total += score[key]
  return total

I am not well-versed about time-complexity and algorithm efficiency yet, so any input would be great, thank you!

or we could use the .get() method. There are multiple ways to solve this problem.

That nested loop is not needed, and greatly affects the time-complexity since it has to iterate the score dict as many times as there are characters in the word. Not a big deal in this case, but something that can be avoided.

dict objects are lookup tables. Give it a key, and it will find the associated value. If the key is not present then it will raise a KeyError.

for char in word:
    total += score[char.lower()]

Using the dict.get() method permits us to evade said key error by supplying a default return value for when a key does not exist.

for char in word:
    total += score.get(char.lower(), 0)

Either way we do not need to iterate the dictionary.

1 Like

This code gives me

Your function fails on scrabble_score(“DuNe”). It returns “2” when it should return “5”.

What is wrong in the code?
Is it correct to call that way to the keys in score?

How could we get a score of 2 for DuNe? well, u and e are both worth one point. Which suggest something doesn’t go right when converting to lowercase

you can confirm this hypothesis by using print:


OK, it doesn’t working…
I thought something was wrong with the loercase.
What is the correct way to do it?

I just succeed, thanks !