I need help wrapping my brain around this logic

Below is the solution code for Code Challenge: Dictionaries

I understand most of it except:

letters[first_letter] += len(names[key])

> # Write your count_first_letter function here:
> 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
> # Uncomment these function calls to test your  function:
> print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))
> # should print {"S": 4, "L": 3}
> print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Sannister": ["Jaime", "Cersei", "Tywin"]}))
> # should print {"S": 7}

can someone explain how

letters[first_letter] += len(names[key])

is matching up “S” in the letters dictionary with the values (first names) that start with the same letter?

I think i just don’t understand the role “key” is playing in len(names[key])

letters is the dictionary name. first_letter is the key for the key: value pair. The += len(names[key]) is adding the number of values in the names dictionary for the specified key. Let’s say when you run the code that your function starts with the"Stark": key (When I ran it on an online editor it actually started with “Snow”: but that’s not really relevant.)
first iteration of your for loop:
key = “Stark”
first_letter = “S” (the character at position 0)
the letters dictionary is still empty, so the if condition resolves to true (“S” is not in letters)
letters[first_letter] = 0 adds a key: value pair to the letters dictionary. The key is “S” and the value is 0, so the letters dictionary is now {"S": 0}
letters[first_letter] += len(names[key]) adds the number of values that are paired with the current key. The current key is “Stark”. There are 3 people listed: "Stark": ["Ned", "Robb", "Sansa"], so the value added to the “S” key in the letters dictionary is 3, so letters is now
{"S": 3} Hopefully that made a little sense :grinning: