I am trying to make a function that will take a character and a histogram and add an instance of that character to the histogram. My code so far is like this:
def add_to_hist(character, histogram):
"""Takes a character and a histogram and adds an occurrence
of that character to the histogram.
string, list -> list"""
for c in character:
if c not in histogram:
histogram[c] = 1
else:
histogram[c] = histogram[c]+1
return histogram
Every time I try to run the code it returns with TypeError: list indices must be integers, not str
. Can anyone help me figure this out? My code actually might be entirely wrong, I'm very new at this. Thanks in advance!
That error is because you are trying to assign a key to a list
, and list
only can be indexed by intenger list[0]
, list[1]
, so on. So, hinstogram
must be a dict
not a list
Make sure when you call add_to_hist
method, pass a dict.
You can init a dict in that way:
histogram = {}
UPDATED
Based on your comment, you can't pass [['B',1],['a',3],['n',2],['!',1]]
as param to add_to_his
, because that is not a dict. It should be {'B':1,'a':3,'n':2,'!':1}