Home > Back-end >  dictionary comprehension code to count the occurances of a word in a string
dictionary comprehension code to count the occurances of a word in a string

Time:10-09

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

CodePudding user response:

use built in library

from collections import Counter
counts = Counter(word.split())
  • Related