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 (Retired) Dictionaries Word Count

My problem: I know how to do for loop over the list, and how to map list-items to keys - then im stuck....

def word_count(string): string = string.lower().split(" ") word_dict = {} for word in string: word_dict[word] = 1 return word_dict

word_count("I am a stupid man and I am a dumb man") --Result----> {'a': 1, 'i': 1, 'stupid': 1, 'man': 1, 'and': 1, 'am': 1, 'dumb': 1}

Any Suggestions?

word_count.py
# 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.

2 Answers

Peter Lawless
Peter Lawless
24,404 Points

The issue appears to be that your word_dict assigns a value of one, and does not iterate up when a word occurs a second time. This means you need to write in two conditions within your for loop, maybe something like:

for word in string:
    if word not in word_dict:
        word_dict[word] = 1
    else:
        word_dict[word] += 1

Thanks for answer(s). In the end i solved it like this:

def word_count(string):
    string = string.lower().split(" ")
    word_dict = {}
    for word in string:
        word_dict[word] = string.count(word)
    return word_dict

I think that, what was my problem - with your kind of (the suggested) approach - was just how exactly to turn the given list into a dictionary (word_dict)