0

I would like to assemble a function that allows me to create a dictionary from a given string or even text file.

For example:

statement = "tell me what you want what you really really want"

I want the end result to look like this:

{tell: 1, me:1, what: 2, you: 2, want: 2, really: 2}

The characters in the string are the keys, while the number of times it appears is the value.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

2

Use collections.Counter(), passing in a sequence of words to count:

>>> from collections import Counter
>>> Counter('tell me what you want what you really really want'.split())
Counter({'you': 2, 'really': 2, 'what': 2, 'want': 2, 'tell': 1, 'me': 1})
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Without importing anything:

statement = "tell me what you want what you really really want"

end_result = dict()

for word in statement.split():
    end_result[word] = end_result.get(word, 0) + 1
wkm
  • 39
  • 7