FAQ: Code Challenge: Dictionaries - Count First Letter


#1

This community-built FAQ covers the “Count First Letter” exercise from the lesson “Code Challenge: Dictionaries”.

Paths and Courses
This exercise can be found in the following Codecademy content:

FAQs on the exercise Count First Letter

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

Hi there all!

Any ideia why this works?

def count_first_letter(names):
dict = {}
[dict.update({key[0] : len(value)}) if key[0] not in dict else dict[key[0]] + dict[key[0]] + len(value) for key, value in names.items()]
return dict

And this doesn’t? returning a SyntaxError: invalid syntax pointing to the +=

def count_first_letter(names):
dict = {}
[dict.update({key[0] : len(value)}) if key[0] not in dict else dict[key[0]] += len(value) for key, value in names.items()]
return dict

Thank you so much for your help,
Best regards from Portugal,
Nuno


#3

Please post a link to this exercise.


#4

Here it is:

https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-dictionaries-cc/exercises/count-first-letter?action=resume_content_item


#5

Hey mft,

Seems like none of the above works, I don’t understand why the else statement gives error.
So the only version I got right was this one:

def count_first_letter(names):
my_dict = {}
for key, value in names.items():
if key[0] not in my_dict:
my_dict.update({key[0] : len(value)})
else:
my_dict[key[0]] += len(value)
return my_dict


#6

Sorry for taking so long. I had to complete the module so I could get to this challenge. Your code when properly indented works as expected.

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

#7

Hey mtf, thank you for your time. Any chance to get it working with some kind of list comprehension, the one below returns error pointing to de +=

def count_first_letter(names):
my_dict = {}
[my_dict.update({key[0] : len(value)}) if key[0] not in my_dict else my_dict[key[0]] += len(value) for key, value in names.items()]
return my_dict


#8

You’ll want to return a dictionary, not a list so a dictionary comprehension would be the tool to reach for, except I’m not sure that will work since we are accumulating to the same keys in the second test example.

This is simplification of your model so we can visualize what the comprehension might look like…

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

The problem being that we cannot look inside a comprehension while it is running so we cannot test for existing key:value pairs.


#9

Thanks a lot for your time mtf! I will, for sure, investigate the dictionaries comprehension.

Complete noob here. Just finished the CS path and the python3 course, began “the Learn Recursion: Python” one, been watching some YT tuts and doing some python training at codewars, what would you advice for me to do next? Data analysis path, machine learning, or…web devolpment (which I want to eventually get to)?

I’ve written a very small program with python that I would like make an APP with, read about kiwi and flask…but not sure.

Thanks again,
Best regards


#10

You’re way ahead of me in completing the CS and Python 3 tracks. I’ve been plugging away at them as time allows. I expect you will get better advice from your peers or coaches as they are more informed than I. Most of my time is spent in the beginner material as I seek out new ways to demonstrate the concepts so learners can understand them. It has somewhat stymied me in the more advanced topics and my old brain can only twist around so much stuff in a day.

Keep up your studies and practice, but as well study up on other areas where your skills may prove useful, or even invaluable. If you have interests in other disciplines then look for ways to cross-pollinate, so to speak. There is hardly a field that cannot still benefit from new ideas and technologies. It just takes the right person(s) to apply their talents.


#11

So far, no peers or coaches to exchange ideas. Thanks for your advice, loved the cross-pollinate concept.
Best regards


#12

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?


#13

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.


#14

Thanks mtf - I didn’t think i caught that above re: why you couldn’t use comprehension. Is below code meant to check to see if the first letter is not already in the created dictionary and if not set the first letter up to the next key? I guess i’m still confused because in the 8th exercise in the section there was a dictionary[value] = 0 piece of code and i’d never seen that before and can’t really understand what’s going on there?
if first_letter not in letters:
letters[first_letter] = 0


#15

In lists, strings, tuples and sets the subscript is an integer indicating the position (index) in the object of the value. All the above are zero indexed, meaning the first element is at index 0.

In dictionaries the subscript can be a number, but may also be a string, and points to the key associated with a value. This exercise involves creating a frequency table or histogram.

list[index]

dictionary[key]