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 (Retired) Dictionaries Word Count

kevin cleary
kevin cleary
4,690 Points

Some of your words seem to be missing

new_str_low  = "I love the holidays".lower()
new_str = new_str_low.split()
new_dict = {}

def word_count(new_str):
  for word in new_str:
    if new_str.count(word) >= 1:
      new_dict[word] = new_str.count(word) 
    else: 
      new_dict[word] = 1 
      word_count(new_str) 
  return(new_dict)

So when I run this code, "Bummer! Some of your words seem to be missing." is what comes back. Any insight? I ran the code in my shell, and this is what comes back

string = 'this is a string'
>>> word_count(string)
{'i': 3, 'a': 1, 'g': 1, 's': 3, 'h': 1, 't': 2, 'n': 1, ' ': 3, 'r': 1}

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

When iterating over a string, each character is looked at individually. So you're for loop is assigning each character to the variable word. You need to split the string into words:

def word_count(new_str):
  new_dict = {}
  word_list = new_str.lower().split()
  for word in word_list:
    if word in new_dict:
      new_dict[word] += 1
    else: 
      new_dict[word] = 1 
  return(new_dict)

By using count you are counting all occurrences multiple times and over writing the previous value each recount.

kevin cleary
kevin cleary
4,690 Points

Ah, yes, that makes perfect sense. Thank you for all your help. I am just starting out, and although I comprehend most of what I'm learning, I still feel a little bit lost sometimes.