Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Word Count

Kishore Kumar
Kishore Kumar
5,451 Points

word_count

Create a function named word_count() that takes a string. Return a dictionary with each word in the string as the key and the number of times it appears as the value.

=========================

my_string = 'I am that I am' for word in my_string.split(): print(word.lower()) i am that i

am

After splitting the string how to count the occurrence of each word and put them into the dictionary with the key,value pair.

2 Answers

Haider Ali
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Haider Ali
Python Development Techdegree Graduate 24,728 Points

Hi, here is my solution to the challenge.

def word_count(string):  #here we define the function word_count which takes 1 argument, a string
  dictionary = {}        #in this line we create an empty dictionary where the words and count will be stored
  a = string.split()     #here, the string is split into all of the individual words and stored in the variable a
  for i in a:            #for each word in the variable/ list a
    if i in dictionary:  #if it is in the dictionary
      dictionary[i] += 1 #add one to the word count
    else:                #however if it is not in the dictionary
      dictionary[i] = 1  #add it to the dictionary and set the word count to 1

  return dictionary      #finally, we return the dictionary

I hope my explanation was clear enough and that you understand now!

Kishore Kumar
Kishore Kumar
5,451 Points

Awesome. Thanks! Haider for the descriptions and the code. K