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

Kai Long Chan
Kai Long Chan
3,238 Points

I cannot pass the wordcount.py . May I have the test case so that I can test my program?

I cannot pass the wordcount.py . May I have the test case so that I can test my program?

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(a_str):
    a_str = a_str.strip()
    a_str = a_str.lower()
    list_word = a_str.split(" ")
    #print(list_word)
    d = {}
    for word in list_word:
        if word not in d.keys():
            d[word] = 1
        else:
            d[word] += 1
    return d

3 Answers

Faster way

def word_count(arg):
    words = arg.lower().split()
    keys = set(words)
    ret = dict(zip(keys, [0 for  _ in range(len(keys))]))
    for key in words:
        if ret.get(key):
            ret[key] += 1
    return ret 
Kai Long Chan
Kai Long Chan
3,238 Points

My problem is fixed. It is because I should use "split()" instead of "split(" ")"

carlos florez
carlos florez
9,664 Points

this worked for me

def word_count(x):
    a = x.lower()
    b = a.split()
    dict1 = {}
    for item in b:
        dict1[item] = b.count(item)
    return dict1

Set will eliminate duplicate keys but this works but will suggest having

for item in set(b)

no need to loop through similar values twice.