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

Python collections word count function challenge.

When I run this code in my python interpreter it works just fine. In this challenge I receive a "Bummer" notice that says to make sure that I am not splitting on only white spaces. I am stuck. Can anyone point me in the right direction?

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.

d = {}
def word_count(string):
    string_list = string.lower().split()
    for word in string_list:
        d[word] = string_list.count(word)
    print(d)

2 Answers

Umesh Ravji
Umesh Ravji
42,386 Points

This ones come up before (for the same reason, maybe the wording of the challenge needs to be improved. It works fine when splitting on whitespace, but it's not explicitly mentioned.

import re

def word_count(string):
    # create your dictionary in here
    d = {}
    string = string.lower()
    # splitting
    string_list = re.split('\s', string)
    for word in string_list:
        d[word] = string_list.count(word)
    # return dictionary at the end
    return d

[Edit] I would just like to add, if you want to consider performance it might be better to keep a total count of each word, rather than using count each time for each word.

# just some pseudo code
    for word in string_list:
        if word in dict:
           total for word += 1
        else
           total for word = 1

Thank you for your answer! It makes sense to me and most importantly it works. I need to do a bit more digging to completely understand the second part of you suggestion but I think that I am almost there. Would I create the key value pair after "total for word += 1" and "total for word = 1" or after the if else statement only? Again, thank you for your answer!

Umesh Ravji
Umesh Ravji
42,386 Points

I think my pseudo code wasn't a good example in this case because of the keywords.

for word in words:
    if word in dictionary:
        dictionary[word] += 1  # already there, increment the total by 1
    else:
        dictionary[word] = 1  # newly added, set to 1

Here's some python you can modify to fit.

Thank you very much! That makes perfect sense.