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

Dileep Pothula
Dileep Pothula
540 Points

How to Pack that to the dictonary

def word_count(string):
    word = string.split()
    for w in word:
        length = len(w)

        D = dict(**{w:length})
        print(D)

word_count("I Want To Learn Python") 

Output:

{'I': 1}
{'Want': 4}
{'To': 2}

Like this I want that in complete dictonary

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}
def word_count(string):
    word = string.split()
    for w in word:
        length = len(w)

        D = dict(**{w:length})
        print(D)

word_count("I Want To Learn Python") 

[MOD: added ``` formatting -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Your approach is looking at the length of characters in each word. The challenge is looking to count how many times each word occurs in the string. Try for each word in the string:

  • initialize an empty dictionary, like, results = {}
  • if the word is not already in the dictionary, if word not in results
  • then add the word to the dictionary with it's initial value 1, results[word] = 1
  • otherwise, increment the existing word's count by oneresults[word] += 1
  • remember to return the results