What does key[0] from the dictionary represent?

Somewhat related question and full disclosure i’m a newbie as well is it correct in assuming the key[0] call is calling on the first key in your dictionary? It does seem truly baffling that the given solution for this exercise doesn’t include a dictionary comprehension no?

In this instance, key is a string, so key[0] is the first letter of the string.

As explained above, we cannot use a comprehension because we need to be able to look inside the object while looping over the names.

Hello everyone!

I solved the exercise (I needed to check the hint, lol, but I did it).

I have one question though.

Why does this one work:

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

But this one doesn’t?

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

What confuses me is this: if you’re checking whether or not key[0] is in letters.keys(), it either is there or it isn’t. Why does else make a difference in this case? What difference does it make in the way that Python iterates through lists or in this case view objects? I feel like it’s an important concept I should understand sooner rather than later.

Thank you so much in advance for your time.

Think of it for a second. The first if may install a key-value, which now exists when the second if is examined. It’s a case of double-dipping which the else case avoids.

Compare the above to this…

def count_first_letter(names):
  first = {}
  for x in names:
    if first.get(x[0]):
      first[x[0]] += len(names[x])
    else:      
      first[x[0]] = len(names[x])
  return first

They are nearly identical, and both use else. Slightly different approach, is all.

2 Likes

Thank you! I understand it now. :smiley:

1 Like

Hey, thanks for your solution! I was also working with .items(), to trying to figure out how to incorporate .get(key[0], 0). Your extra line, print(key, value), helped me visualised how the solution quickly. Pared it down to 6 lines of code, kudos!

Took me a second to figure out what I was doing wrong and it was that I accidentally had my return statement indented… Those little things!