Create dictionary of unique words from spam emails and ham emails ( list comprehension)

Screen Link: Learn data science with Python and R projects
I try to change my for loop to list comprehension about creating a dictionary. but i am not sure if my code is correct when i use list comprehension. I also dont understand the code below from the solution. parameters_spam = {unique_word:0 for unique_word in vocabulary} if i want to change it to for loop code…what it will be? Thank you.

My Code:

u={}
for word in vocabulary:
    if word in u:
        u[word]+=1    
    else:
        u[word]=0
#list comprehension 
{(u[word] += 1 if word in u else uu[word]=0) for word in vocabulary }

Hi @candiceliu93, I remember trying to do something similar before and had to dig deep to “find” it again!

If you want to use a dictionary comprehension instead of a for loop, you could use something like this:

u = {key: vocabulary.split().count(key) for key in set(vocabulary.split())}

This little bit of code is essentially just a dictionary comprehension that initializes a dictionary with all of its values set to 0