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

angel moreta
angel moreta
2,912 Points

Hi, I need someone to guide me a little with this problem :)

ok, I'm trying to find the way to count for every word that is repeated inside my string. please read my code carefully, i've been struggling since this morning with this problem but i know i am not too far to get through it :)

here's my output in my terminal: {'i': 8, 'do': 3, 'not': 4, 'like': 5, 'it': 6, 'sam': 7, 'am': 9} <----- i was also wondering why is giving me those values.

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.
strg = "I do not like it Sam I Am".lower()
strg = strg.split()

def word_count(string):
    value = 1
    empty_dict = {}

    for each_word in string:
        if each_word == each_word:
            value +=1
        if each_word in string: 
            filled_key = empty_dict.update({each_word:value}) 
        else:
            pass

    return empty_dict




print(word_count(strg))

1 Answer

Instead of incrementing a value variable per for loop iteration I would use the count() function on each word against the sentence list. :D

https://www.tutorialspoint.com/python/list_count.htm

angel moreta
angel moreta
2,912 Points

Dude !!!!! you are the man, i didnt even know we had such func in python thank you so much, i solved the problem :DDDD