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 am stuck, how to return a Dictionary from a string?

The only way I count figure out is to use some library called collections. but it does not return the values required to pass the task. I hope someone can explain this for me!

Actually Treehouse team did not focus well on this topic!

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 (x):
    listb=[]
    lista=[]
    countt=0
    counter=[]
    lista=x.split()
    count=Counter(lista)
    return count

1 Answer

Steven Parker
Steven Parker
229,921 Points

Maybe a few hints will help get you going:

  • you could start with a new, empty dictionary
  • splitting the string in a list was a good idea, you could then use the list in a loop
  • in the loop you could check if the word is in the dictionary already
  • for a word in the dictionary, you could increment the associated value
  • if the word is not in the dictionary, you could add it with a value of 1
  • after the loop finishes, you could return the dictionary