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

Create a function named word_count() that takes a string.

I can't figure this out for the life of me can someone help me!

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.

This is what I've got:

# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.

[My Code]

string_sict = {}
for word in split_string():
    if word in string_dict[word]:
        string_dict[word] += 1
    else:
        string_dict[word] = 1

6 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Your code looks fine except you misspelled string_dict the first time you used it. Well, and split_string() isn't a built-in function. You'll need to split the string yourself using .split() on the string.

Thanks that helped, there's a lot of words I spell wrong sometime with typing fast or because we spell the word differently in England! Ha.

I could not understand this.

Could I ask how this is separating keys and values. Thats the only part im not seeing in the answers

There's a really handy list method that I found in the docs when doing that code challenge. It's called [].count(x), Where x is the item that you want to check how many times it appears in the list.

For example: [1, 2, 3, 2, 1].count(1) = 2

Does that help?

This is the code that I wrote:

def word_count(sentence):
    new_dict = {}
    word_list = sentence.split()
    count = 0

    for original_word in word_list:
        if original_word not in new_dict:
            count = 0
            for comparison_word in word_list:
                if original_word == comparison_word:
                    count += 1
                    new_dict.update({original_word: count})
    return new_dict

I'm not sure the nested for loop is necessary; there may be a simpler way to do it... but this was the method I went with anyway.

Hey Mark, I like how you used the .update(). When I first tried this challenge, I figured that update should be included, but had no clue how to do it. Just came across your code now. I'm gonna dissect it to see what makes it tick :D

OK Mark, I took you idea and did it without the extra for loop. It didn't cut down on the lines of code like I thought it might. But your idea launched me into a new way of looking at it. Thanks :D

def word_count(s):
    dct_cnt = {}
    count = 0
    list_s = s.split()
    for word in list_s:
        if word in dct_cnt:
            count +=1
            dct_cnt.update({word: count})
        else:
            count = 1
            dct_cnt.update({word: count})
    return dct_cnt

I think your idea is more readable and makes more sense than the prevailing ideas. Everyone else went with:

count[item] += 1
# instead of
dct_cnt.update({word: count})

Thanks Kenneth! After 1 hr of feeling really dumb I got it.

def word_count(my_word):

my_dict = {} my_list = my_word.lower().split()

for word in my_list: my_dict[word] = my_list.count(word) print(my_dict)

word_count("I am that I am")

Simpler. :) Just that you would have to replace the print(my_dict) with return(my_dict).

My code works outside of workspaces, but i get an error when trying to submit it as a solution in workspaces.

(Error is: "Hmm, didn't get the expected output").

Can anyone suggest what i've done wrong here?

def word_count(sentance):
    words = sentance.lower().split(' ')
    returndict = {}
    for word in words:
        if word in returndict:
            returndict[word] += 1
        else:
            returndict[word] = 1
    return returndict

thanks a million.

what is my fault. I could not find any resolve .

word_count = {}
for word in word_count.split():
    if word in word_count[word]:
        word_count[word] += 1
    else:
        word_count[word] = 1
Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You're only using a single variable,word_count for everything. First it's an empty dictionary. Then you try to .split() it (which can only be done on strings). Then you're back to using it like a dictionary.