The code I have below is supposed to run the number of words that start with a certain letter, but when I run it, the counts are all 0, instead of what they should be: {'I': 2, 'b': 2, 't': 3, 'f': 1}. I appreciate any help. Thanks!
def initialLets(keyStr):
'''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper
and lower case letters should be considered different letters.'''
inLets = {}
strList = keyStr.split()
firstLets = []
for words in strList:
if words[0] not in firstLets:
firstLets.append(words[0])
for lets in firstLets:
inLets[lets] = strList.count(lets)
return inLets
text = "I'm born to trouble I'm born to fate"
print(initialLets(text))
3 Answers 3
You can try this:
text = "I'm born to trouble I'm born to fate"
new_text = text.split()
final_counts = {i[0]:sum(b.startswith(i[0]) for b in new_text) for i in new_text}
Output:
{'I': 2, 'b': 2, 't': 3, 'f': 1}
Comments
You don't have a counter as you append the letter but not its number of occurrences.
So to simplify:
def initialLets(keyStr):
'''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper
and lower case letters should be considered different letters.'''
strList = keyStr.split()
# We initiate the variable that gonna take our results
result = {}
for words in strList:
if words[0] not in result:
# if first letter not in result then we add it to result with counter = 1
result[words[0]] = 1
else:
# We increase the number of occurence
result[words[0]] += 1
return result
text = "I'm born to trouble I'm born to fate"
print(initialLets(text))
Comments
Firstly, you are checking if the first letter of the word is in the list before putting it in. That would just make the list comprise of only 1 of each letter. Secondly, your strList is a list of each word, instead of inLets[lets] = strList.count(lets), it should be inLets[lets] = firstLets.count(lets)... While your current code isn't the cleanest way to do it, this minor modification would have worked.
def initialLets(keyStr):
'''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper
and lower case letters should be considered different letters.'''
inLets = {}
strList = keyStr.split()
firstLets = []
for words in strList:
firstLets.append(words[0])
for lets in firstLets:
inLets[lets] = firstLets.count(lets)
return inLets
text = "I'm born to trouble I'm born to fate"
print(initialLets(text))