Tam
Tam

Reputation: 105

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

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

Upvotes: 0

Views: 146

Answers (2)

RUDRAGOWDA
RUDRAGOWDA

Reputation: 1

'''Using dictionary comprehension 1st character and its count 2nd character and count if repeated more than once'''

str="I am looking to make it into a comprehension if possible.."

ch_its_count={ch:str.count(ch) for ch in str}
print(ch_its_count)

ch_count_for_repeated={ch:str.count(ch) for ch in str if str.count(ch)>1}
print(ch_count_for_repeated)

Upvotes: 0

X3R0
X3R0

Reputation: 6324

use built in library

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

Upvotes: 2

Related Questions