Search code examples
pythondictionarypacking

Trying to create a word count function


I'm trying to create a function:

word_count("I do not like it Sam I Am")

gets back a dictionary like:

{'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}

I've no idea how to begin.


Solution

  • def word_count(sentence):
      d = sentence.lower().split()
      d = {x: d.count(x) for x in d}
      return d