This is from one of the Python Code Challenges in the Intro to Programming unit of the Computer Science pathway. Link to the page. The goal is to take a dictionary that has last names as the key and a list of corresponding first names as each value, and return a new dictionary with the last initial as the key and the number of people with that same last initial as the value.
Here’s my code.
def count_first_letter(names):
return {key[0]: len([first_name for first_name in names.values() if first_name[0] == key[0]]) for key in names}
print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))
The print statement should return {‘S’: 4, ‘L’: 3}, but instead returns {‘S’: 0, ‘L’: 0}.
I spent a good amount of time trying to figure this out before posting this. I know there are other ways to solve this challenge, but I’m hoping learn where I’m going wrong with the comprehension. Thanks in advance for any help.