dictionary comprehension code to count the occurances of a word in a string

Question:

I am learning about list and dict comprehensions and for most of the simple cases I am OK.

I have the following code that counts the occurrences of a word in a string. I am looking to make it into a comprehension if possible..

Can it be done?

st_dict={}
for word in words:
   if word in st_dict:
      st_dict[word] +=1
   else:
    st_dict[word] =1
Asked By: Tam

||

Answers:

use built in library

from collections import Counter
counts = Counter(word.split())
Answered By: Dean Van Greunen