How does accessing the first letter work?

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

I don’t understand the bolded part from the code solution

It simply checks if the attribute already exists, and if not, then set it.

I am having trouble understanding how this line works: letters[first_letter] += len(names[key])

Why does this give the correct value for the key? I am struggling with this concept. In my mind it should be getting the length of the each Key in the dictionary names.

Can anyone walk me through this concept of how I am getting the number of values with the first letter (as needed) instead of the key length?

Its just not making sense to me… I am missing something… Thanks!

1 Like

Wouldn’t that be len(key) ? Not sure what you mean.

Have you thought through what value you’re sending to len?

Nope. I wasn’t thinking through the value I was sending to length. Thank you! I misunderstood the challenge. I was thinking that I was counting the number of people who had the first letter of their name starting with the first letter of the last name. I confused myself real good. I went through with fresh eyes this morning and saw my mistake in comprehension.

Thank you for the quick response!!

Could it have been solved also by .count() method somehow? (counting the first letters, instead of using the len?)

Is that an action that makes sense if you describe it in english? start with that before considering how to implement it, from your wording I’m not convinced you’ve thought through what you mean

Does this count as low effort or is this what the function should look like?

def count_first_letter(names):
  new_dict = {}
  for x in names.items():
    if x[0][0] in new_dict:
      new_dict[x[0][0]] += len(x[1])
      new_dict[x[0][0]] = len(x[1])
  return new_dict

The function (although not intended to be) is very similar to the frequency question teh course had a few questions ago where you had to find out teh number of times a value is shown within a dictionary.