-1

I'm having trouble transforming every word of a string in a dictionary and passing how many times the word appears as the value. For example

string = 'How many times times appeared in this many times'

The dict i wanted is:

dict = {'times':3, 'many':2, 'how':1 ...}
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
  • Show your own (effort and) code properly formatted in the question. – Michael Butscher May 19 '20 at 16:45
  • Does this answer your question? [How do I count unique words using counter library in python?](https://stackoverflow.com/questions/55987421/how-do-i-count-unique-words-using-counter-library-in-python) – DarrylG May 19 '20 at 16:48

2 Answers2

3

Using Counter

from collections import Counter
res = dict(Counter(string.split()))
#{'How': 1, 'many': 2, 'times': 3, 'appeared': 1, 'in': 1, 'this': 1}
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

You can loop through the words and increment the count like so:

d = {}
for word in string.split(" "):
   d.setdefault(word, 0)
   d[word] += 1
kudeh
  • 883
  • 1
  • 5
  • 16