-1

How can I make a function (given a string sentece) that returns a dictionary with each word as key and the number of occurrence as the value? (preferably without using functions like .count and .counter, basically as few shortcuts as possible.)

What I have so far doesn't seem to work and gives a key error, I have a small clue of why it doesn't work, but I'm not sure what to do to fix it. This is what I have for now:

def wordCount(sentence):
    myDict = {}
    mySentence = sentence.lower().split()

    for word in mySentence:
        if word in myDict:
           myDict[word] += 1
        else:
           myDict[word] = 1

    return myDict
wordCount("Hi hi hello")
print(myDict)
Charlotte
  • 55
  • 1
  • 2
  • 7
  • 1
    In `if word in mySentence:` probably you meant `if word in myDict:`. – jdehesa Sep 19 '18 at 15:33
  • Also, if this is not a programming exercise, you can use [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) to solve this problem: `Counter(sentence.lower().split())`. – jdehesa Sep 19 '18 at 15:34

1 Answers1

1

You have been mixing up variables mySentence and myDict at one point.
You can also not use local variables outside of their scope. The following will work:

def wordCount(sentence):
    myDict = {}
    mySentence = sentence.lower().split()
    for word in mySentence:
        if word in myDict:
           myDict[word] += 1
        else:
           myDict[word] = 1
    return myDict

d = wordCount("Hi hi hello")  # assign the return value to a variable
print(d)  # so you can reuse it
user2390182
  • 72,016
  • 6
  • 67
  • 89