Search code examples
pythondictionaryreturnfind-occurrences

How to return dictionary with occurrence per word in a string (Python)?


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)

Solution

  • 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