Count Words - Dictionary

We’ll count the occurrence of every word using a dictionary

Every Word


  • Count the occurrence of every word in our string using a dictionary
# Count words in a String using Dictionary

# Define the function
def freq(string):
    
    #step1: A list variable is declared and initialized to an empty list.
    words = []
    
    #step2: Break the string into list of words
    words = string.split() # or string.lower().split()
    
    #step3: Declare a dictionary
    Dict = {}
    
    #step4: Use for loop to iterate words and values to the dictionary
    for key in words:
        Dict[key] = words.count(key)
        
    #step5: Print the dictionary
    print("The Frequency of words is:",Dict)

    
# Call the function and pass string in it
freq("Mary had a little lamb Little lamb, little lamb Mary had a little lamb.Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
Everywhere that Mary went The lamb was sure to go")
The Frequency of words is: {'Mary': 6, 'had': 2, 'a': 2, 'little': 3, 'lamb': 3, 'Little': 1, 'lamb,': 1, 'lamb.Its': 1, 'fleece': 1, 'was': 2, 'white': 1, 'as': 1, 'snow': 1, 'And': 1, 'everywhere': 1, 'that': 2, 'went': 3, 'went,': 1, 'Everywhere': 1, 'The': 1, 'sure': 1, 'to': 1, 'go': 1}

One Word


Count the occurrence one one key/word passed as argument we just edit the above code block slightly to

  • include the passed key as argument and test for it conditionally
# Count the occurrence of one key/word in a String using Dictionary

# Define the function
def freq(string,passed_key):
    
    #step1: A list variable is declared and initialized to an empty list.
    words = []
    
    #step2: Break the string into list of words
    words = string.split() # or string.lower().split()
    
    #step3: Declare a dictionary
    Dict = {}
    
    #step4: Use for loop to iterate words and values to the dictionary
    for key in words:
        if key == passed_key:       # count the occurrence only if condition is True
                Dict[key] = words.count(key)
        
    #step5: Print the dictionary
    #print(f"{passed_key} Occurs: ",Dict," times")
    # The above prints out: little Occurs: {'little': 3} times
    
    # Let's just print out the count of occurrence without the dictionary
    print(f"{passed_key} Occurs: ",Dict[passed_key]," times")

    
# Call the function and pass string in it
freq("Mary had a little lamb Little lamb, little lamb Mary had a little lamb.Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
Everywhere that Mary went The lamb was sure to go","little")
little Occurs:  3  times