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

Ronit Mankad
Ronit Mankad
12,166 Points

Tell me my mistake!

Plz tell me my mistake!

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(st):
    word_dict = {}
    for word in st.split():
        word_dict[word.lower()] = st.count(word)
    return word_dict

2 Answers

Modou Sawo
Modou Sawo
13,141 Points

Hi Ronit, Using an if condition and an "in" statement is perhaps a cleaner way. Create two variables: one you split the string and lowercase it & the other which would contain the returned output(my case I called it new_dict)

def word_count(arg):
    output = arg.lower().split()
    new_dict = {}
    for item in output:
        if item in new_dict:
            new_dict[item] += 1
        else:
            new_dict[item] = 1
    return new_dict
Doc Collins
Doc Collins
7,087 Points

Hi Ronit:

Your code worked for me.

Microsoft Windows [Version 10.0.10586] (c) 2015 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.

def word_count(st): ... word_dict = {} ... for word in st.split(): ... word_dict[word.lower()] = st.count(word) ... return word_dict ... word_count("hello world") {'world': 1, 'hello': 1} word_count("hello world. it's time to go") {'go': 1, 'hello': 1, 'to': 1, 'world.': 1, "it's": 1, 'time': 1}