Python Dictionaries


I am working on question 4, Python Code Challenges: Dictionaries (Advanced) section, Python Code Challenges II lesson of the Python 3 course.

Below is the solution to the challenge.

def count_first_letter(names):
  letters = {}
  for key in names:
    first_letter = key[0]
    if first_letter not in letters:
      letters[first_letter] = 0
    letters[first_letter] += len(names[key])
  return letters

And the answer to

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

is {'S': 4, 'L': 3} .

What I’m not understanding is the second to last line of code in the solution. How does Python know that the first 4 values go to the S key and the last 3 values go to the L key? When I print len(names[key]) in the for loop it prints 3 1 3. I assume Python is adding the (first) 3 and the 1 to the S and the (second) 3 to the L. How does it know to do that? Why doesn’t it add all of them to both S and L so it prints ``{‘S’: 7, ‘L’: 7}` ?

Thank you.


This first becomes S, which is the key in the letters dictionary to receive an initial zero, if it is new. That encounter and all others will increment that value. The other key is L. Same process, only incrementing that key’s value.

1 Like

I get it now, thanks. I was making the mistake of seeing that second to last line in isolation, vs. seeing it as the last step in the iterative process of the for loop.