Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries Word Count

dictionary challenge word count-unable to find solution that passes the challenge

Challenge Task 1 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. PLEASE LET ME KNOW WHERE IS THE BUG IN CODE

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()
    word_dict = {}
    word_list = string.split(" ")
    for sel_word in word_list:
        count = 0
        for word in word_list:
            if sel_word == word:
                count +=1
        word_dict[sel_word] = count
    return word_dict

14 Answers

You need to change this line of code:

word_list = string.split(" ")

To this:

word_list = string.split()

The difference is that .split(" ") splits only on spaces and .split() splits on all whitespace. Whitespace includes spaces, tabs, newlines, vertical spaces, etc.

The challenge expects you to split on all whitespace. :smile:

Everything else in your code looks great and is very clean and easy-to-read. Congrats! :tada: :confetti_ball: :tada:

I hope this helps :grin:

Happy coding! :sparkles:

:dizzy: ~Alex :dizzy:

Thanks for the solution, it worked.

I wish there were more examples to test with so I could have figured this out on my own, but thanks for explaining that. In future, I will try harder to break my code.

Thanks.

uhh, davison !! By doing it with above method, why it didn't produce the following output:- {'i': 2, 'i': 2, .......others as given} because in outer for loop it checked 'i' 2 times as the word_list = [] is this ['I' ,'do', 'not' ,'like', 'it', 'Sam' ,'I', 'Am']

Jan Giemza
Jan Giemza
32,959 Points

I did it this way, with two simple for loops. Hopefully, this is easy to read and understand.

def word_count(string):
    words = string.lower().split()
    dictionary = {}
    for word in words:
        dictionary[word] = 0
    for word in words:
        dictionary[word] += 1
    print(dictionary)
    return dictionary

word_count("I do not like it Sam I Am")

I like your way :)

I like yours than the others. Thanks a lot!!! Although the last part of

print(dictionary) return dictionary

It could be either one, right?

Thanks again :)

Sohail Mirza
seal-mask
.a{fill-rule:evenodd;}techdegree
Sohail Mirza
Python Web Development Techdegree Student 5,158 Points

Hi, could someone explain the above code by Jan. I want to know what know the following 1, What does each of the for in loop do in other others word what is it outputting 2, i don't understand the this [word] means

Mark Tripney
Mark Tripney
6,009 Points

The count() method makes this relatively straightforward. I've included some comments which might make things clearer...

def word_count(a_string):
    # Convert 'a_string' into lower case and break it up into a list
    words = a_string.lower().split()
    # Declare an empty dictionary, ready to be populated
    dictionary = {}
    # For each item in the list, use the 'count()' method to tally how
    # often it appears. Then, populate the dictionary with a key (the word)
    # and its corresponding value (the count).
    for word in words:
        dictionary[word] = words.count(word)
    return dictionary

print(word_count("I do not like it Sam I Am"))

I think yours is the best! super clear by using a single line to assign value (words.count) to keys(word)

found this to work also

import collections 

def word_count(astring):
    newstring = astring.lower().split()
    return collections.Counter(newstring)

Same what I did,

Cristian Romero
Cristian Romero
11,911 Points

Love this answer.. I think it's important to start thinking imports to make the work easier..

def word_count(string):
    string = string.lower()
    new_dict = {}
    for i in string.split():
        new_dict[i] = string.split().count(i)
    return new_dict

I tried using the count method for list.

Jonathan Peters
Jonathan Peters
8,672 Points

I love this solution, thanks for this!

thank you Pansari

Vlad Bitca
PLUS
Vlad Bitca
Courses Plus Student 2,702 Points

You can try:

from collections import Counter
def word_count(sentence):
    return Counter(map(str, sentence.lower().split()))

this one work smooth as well thanx

def word_count(proposition):
    words = proposition.lower().split()
    word_freq = {}
    for w in words:
        try:
            word_freq[i] += 1
        except KeyError as ke:
            word_freq[i] = 1
    return word_freq

Alexander Davison :Request your help in finding the bug in my solution for word_count

this code works. what kind of bug?

As Alex mentioned .split(" ") splits only on spaces and .split() splits on all whitespace, the code challenge is expecting for whitespaces and my code was only splitting on spaces.

def word_count(string): dic = {} array = string.lower().split() for each in array:

    dic[each] = array.count(each)
print(dic)

this seems to work on python but it's not accepted as a correct solution on teamtreehouse!

Nevermind replace print() with return and it is now acceptable answer.

def word_count(item):
    dic={}
    item=item.split()
    for i in item:
        dic[i.lower()]=dic.get(i.lower(),0)+1
    return dic

My apologies not sure how to post my code like the rest of you guys...but if anyone please explain why this code isn't accepted.i get no help other than "Bummer: try again " lol. plesae i will use your guys example because i spent 3 days tryna do this on my own it works in my repl.it so just anything would be appreciated

def word_count(my_string): my_string = my_string.lower() dic = dict() for w in my_string.split(): if w in dic.keys(): dic[w] = dic[w]+1 else: dic[w] = 1 return dic

This worked for me. made 2 lists and did zip :

def word_count(kent):  
    kent=kent.lower().split()  
    L=[]  
    for k in kent:  
        L.append(kent.count(k))  
    dkent = dict(zip(kent, L))  
    return(dkent)
def word_count(string):
    string=string.lower()
    string_list=string.split(" ")
    string_dict={}
    for word in string_list:
        if word in string_dict:
            value= string_dict.get(word)
            string_dict[word] = value+1
        else:
            string_dict.update({word:1})
    return (string_dict)

I do not understand why this code does not pass the test

Don't forget to split on all whitespace (spaces, tabs, newlines, vertical spaces, etc) like Alexander Davison mentioned above. Currently, you are using .split(" ") which is splitting ONLY on spaces.

use .split() instead of .split(" ")