Dictionary Key Error

def count_first_letter(names):
  letter_count = {}
  for key, value in names.items():
    if key[0] in letter_count.keys():
      letter_count[key] += len(value) 
    else:
      letter_count[key[0]] = len(value)
  return letter_count
print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], 
                          "Snow" : ["Jon"],
                          "Lannister": ["Jaime", "Cersei", "Tywin"]}))
# should print {"S": 4, "L": 3}

ERROR:

  File "script.py", line 6, in count_first_letter
    letter_count[key] += len(value) 
KeyError: 'Snow'

When you iterate for-loop, double check the iteration value of key. (comment out the conditionals)

Start from there, that should get a lot of debugging going.

3 Likes

Hey @sumeet8910 it’s been a little while since you originally posted this question. Could you come back to let us know if the above reply helped you?

In line 6 you forgot to select the first letter, so the codes think that you’re updating the value of a key named Snow that doesn’t exist.

def count_first_letter(names):
    letter_count = {}

    for key, value in names.items():
        if key[0] in letter_count.keys():
            letter_count[key[0]] += len(value) 
        else:
            letter_count[key[0]] = len(value)
    return letter_count

print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], 
                          "Snow" : ["Jon"],
                          "Lannister": ["Jaime", "Cersei", "Tywin"]}))

Output:

{'S': 4, 'L': 3}
1 Like