C3 W1 Exercise 8

I am trying to assign the nested dictionaries and I am using:

word_freq_dict = {word: {‘spam’: 0, ‘ham’: 0}}

where I am looping over each word - so I am not using a nice key label but a variable. I don’t know if that is the issue as dictionaries are new to me.

I am getting this error: TypeError: unhashable type: ‘list’

Any help is greatly appreciated

The only way to add a key- value pair to a Python dictionary (as far as I know) is:

dict_name[key] = { ... }

Maybe there is another format, but this way above will certainly work. Try it and tell us :slight_smile:

P.S. in this case, the value is another dictionary and I guess you know it according to your code. But I wanted to avoid any misunderstandings.

I tried:
word_freq_dict[word] = {‘spam’: 0, ‘ham’: 0}

I am still getting the same error.

Yes… Maybe the error is due to something before.

I remember to struggle with the first for loop, with that strange “iterrows()” that I’ve never seen before.

Check if you coded correctly these phyton commands:

  1. In the first for loop you’ll iterate over the data frame rows.
    e.g. “for row_i in data_frame.iterrows():”

  2. In the second loop you’ll iterate over the elements (words) of a specific column which contains the lists of words.
    e.g. “for word in row_i[‘column_name’]:”

  3. Now that you get word by word, check if it is already in the dict.
    e.g. “if word not in dict:”

Try to compare to your code and tell me the results.

I think my loops are okay but here is what I have

for _, row_i in df.iterrows():
for word in row_i[‘words’]:
if word not in word_freq_dict:
word_freq_dict[word] = {{‘spam’: 0, ‘ham’: 0}}

i’m getting the error: unhashable type: dict

Thank you for helping me.

One last thing, try removing the excess of curly braces from the last line of code.

Just {‘spam’ = 0, ‘ham’ = 0}.

Hope it runs. I ran out of suggestions :frowning:

Actually it would be:
if word not in word_freq_dict.keys():

The .keys() part is not necessary as long as in is used. Source

Hi @Tom_Pham
Actually if you expand word_freq_dict, dictionary the words are keys and the number of times those words occur in either spam or ham are values.

In python to get the names of keys of a dict you use .keys() which is we need in this case.
In order to get those values we use .items().

For further information please refer python dictionaries, there are many good articles online.