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

Tyler Nordmann
Tyler Nordmann
1,083 Points

Help with Word Count. My function returns what I think is correct, but upon submission it fails.

def word_count(phrase):
    space_index = []
    key_list = []
    phrase = phrase.lower()
    count = 1

    for letter in phrase:
        upto = phrase[0:count]
        if letter == " ":
            space_index.append(len(upto)-1)
        count += 1

    count = 0
    key_list = [phrase[0:space_index[0]]]
    for num in space_index:
        try:
            nums = space_index[count:count+2]
            key_list.append(phrase[nums[0]+1:nums[1]])
            count += 1
        except IndexError:
            continue

    key_list.append(phrase[space_index[len(space_index)-1]+1:len(phrase)])

    counter = []
    count= 0
    for num in key_list:
        counter.append(count)

    count = 0
    for item in key_list:
        for thing in key_list:
            if thing == item:
                counter[count] += 1
        count += 1

    my_dict = dict(zip(key_list, counter))
    return my_dict
Nikolay Nogin
Nikolay Nogin
22,154 Points

As said Kenneth in the future courses, Maybe you need to look at editing? :) I mean, try to understand this code or find another solution here on forum, and you won't have to make a mountain out of a molehill:

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

You have done a great job, but try to simplify your code. Below you can find my code which works, please study it and see if you can gain anything from it. This code works but I also need find a way to simplify it even further.

myword ="I do not like it Sam I Am"

def word_count(sentence):
  my_dict = {}
  sentence = sentence.lower().split()
  for sen in sentence:
    if sen in my_dict:
      count = my_dict[sen] + 1
      my_dict[sen] = count
    else:
      my_dict[sen] = 1
  return my_dict