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

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

i am trying to solve this one my way, but i am not successful at it yet. I wold appreciate some pointers please.

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):
    new_dict = {}
    key_count = []
    string = string.lowercase()
    word = key
    for key in string.key():
        key_count = 1
        if key in key_count:
            key_count +=1
        else:
            continue


    return {new_dict}

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

Your latest code is close, but needs the following corrections:

  • the for loop should loop over string_list not string_list() as it is not a function
  • the if should look for word in new_dict
  • when referring to elements of new_dict use square brackets: new_dict[word]
  • on style, since word_count is only used as the constant 1, the number can be used directly, or define the variable to be more representative of the constant, say, init_word_count and move the definition to the beginning of the function.

Post back if you need more help. Good luck!!!

Hey mamadou! Big tip here! Strings dont have a .key attribute! Also .lowercase does not exist in python (should be .lower())

i made more correction here, and still not working

def word_count(string):
    new_dict = {}
    word_count = []
    string_list = string.lower().split()


    for word in string_list():
        word_count = 1
        if word in word_count:
            new_dict(word) +=1

        else:
            new_dict(word)= word_count

    return new_dict

[MOD: added ```python formatting -cf]