Python. How do I return a dictionary that counts occurrences in a list of strings?
I am trying to create a function that takes into account occurrences of the first letters in a list of strings and returns them as a dictionary.
For example:
list = ["banana", "ball", "cat", "hat"]
Vocabularywill look like this: {b: 2, c: 1, h: 1}
Here is the code I have that is iterating but not properly accounted for. This is where I get stuck. How do I update the values to be calculated?
def count_starts(text):
new_list=[]
for word in range(len(text)):
for letter in text[word]:
if letter[0]=='':
new_list.append(None)
else:
new_list.append(letter[0])
new_dict= {x:new_list.count(x) for x in new_list}
return new_dict
Also how can I avoid an out of range error given the following format:
def count_starts(text):
import collections
c=collections.Counter(x[0] for x in text)
return c
Also, what do I need to do if the list contains "None" as the value? I need to count. No.
source to share
The problem with your code is that you seem to be repeating all the letters of that word. letter[0]
- a substring of a letter (which is a string).
You will need to make it easier, no double loop needed, take every first letter of your words:
for word in text:
if word: # to filter out empty strings
first_letter = word[0]
But once again collections.Counter
with the understanding of the generator for extracting the first letter is the best choice and one-liner (with added condition to filter out empty lines):
import collections
c = collections.Counter(x[0] for x in ["banana","ball", "cat", "", "hat"] if x)
c
is now a dict: Counter({'b': 2, 'h': 1, 'c': 1})
one option is to insert None
instead of filtering empty values:
c = collections.Counter(x[0] if x else None for x in ["banana","ball", "cat", "", "hat"])
source to share
my_list=["banana","ball", "cat", "hat"]
my_dict = dict()
for word in my_list:
try:
my_dict[word[0]] += 1
except KeyError:
my_dict[word[0]] = 1
This increments the key value by 1 for an already existing key, and if the key was not found before it was created with a value of 1
Alternative:
my_list=["banana","ball", "bubbles", "cat", "hat"]
my_dict = dict()
for word in my_list:
if word[0] in my_dict.keys():
my_dict[word[0]] += 1
else:
my_dict[word[0]] = 1
source to share