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

I have no idea what I'm doing

Here's my code. I have no idea what exactly the challenge is asking me to do, but I have a decent idea. Can any of you guys help me out? Thanks in advance.

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.

string_dict = "{i} {am} {that} {i} {am}"

split_string = string_dict.split()

def word_count(string):
    string = string.lower()
    new_string = string.split(' ')
    final = {}
    for key in new_string:
        if key in final:
            final[key] += 1
        else:
            final[key] = 1
    return final

1 Answer

Hi there, I am sure there are better ways to do this - however here was my answer

def word_count(my_str):

    t_list = my_str.lower().split()   # create a list to iterate through
    n_dict = {}                       # this will be the returned dictionary
    t_dict = {}                       # temporay dict to hold the key and value

    for x in t_list:                  # iterate through the list 
        x_ctr = 0                     # set a counter to 0 this will hold the value  
        for y in t_list:                
            if x == y:                # if we find a similar value add 1 to the count
                x_ctr += 1
        t_dict = {x : x_ctr}          # create a temp dict with the key and value
        n_dict.update(t_dict)         # append the temp dict to the final dict
    return n_dict


if __name__ == "__main__":

   print(word_count('I do not like it Sam I am'))

Hopefully this is easily readable, if not please ask me a question