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 (2016, retired 2019) Dictionaries Word Count

Challenge Task of 1

Alright, this one might be a bit challenging but you've been doing great so far, so I'm sure you can manage it.

I need you to make a function named word_count. It should accept a single argument which will be a string. The function needs to return a dictionary. The keys in the dictionary will be each of the words in the string, lowercased. The values will be how many times that particular word appears in the string.

Check the comments below for an example.

wordcount.py
# E.g. 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}
# Lowercase the string to make it easier.
def word_count(string):
    string = string.lower()
    return { a:string.count(a) for a in set(string.replace(' ','')) }

1 Answer

Jonathan Fernandes
PLUS
Jonathan Fernandes
Courses Plus Student 22,784 Points

I find that it is easier if you split what you want to do up conception-ally.

The main point is you need to be able to do the following:

  • take a string and make it all lowercase
  • separate those strings into words
  • go through each word and add them to the dictionary with the value of 1
  • if you come across a word that is already in the dictionary, increment the value by one
  • return the string
def word_count(string):
    # take a string and make it all lowercase
    string = lower()

    # separate those strings into words
    string = string.split(' ')

    # go through each word and add them to the dictionary with the value of 1
    response = {}
    for item in string:
        if item in response:
            # if you come across a word that is already in the dictionary, increment the value by one
            response[item] += 1
        else:
            response[item] = 1
    # return the string
    return response

Does that help seeing it broken up into little pieces?

I had a very similar code to yours but it doe not seem to take it

def word_count(string):
    string=string.lower()
    string_list=string.split(" ")
    string_dict={}
    for word in string_list:
        if word in string_dict:
            string_dict[word] += 1
        else:
            string_dict.update({word:1})
    return (string_dict)