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