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

Nikola Jankovic
Nikola Jankovic
10,793 Points

This is working well in my editor but here it is not good. Anybody knows why?

def word_count(string):
    list1 = string.lower().split()
    new_dict = {}
    number_count = 1
    for x in list1:
        number_count= 1
        if x in new_dict:
            number_count += 1
        else:
            number_count = 1

        new_dict.update({"{}".format(x): number_count})

    return new_dict
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(string):
    list1 = string.lower().split()
    new_dict = {}
    number_count = 1
    for x in list1:
        number_count= 1
        if x in new_dict:
            number_count += 1
        else:
            number_count = 1

        new_dict.update({"{}".format(x): number_count})

    return new_dict
Nikola Jankovic
Nikola Jankovic
10,793 Points

When it ends with print(new_dict) instead of return new_dict it is working well

2 Answers

Jason Mollerup
Jason Mollerup
2,683 Points
def word_count(arg):
    words = arg.lower().split()
    num_words = {}
    for word in words:
        if word in num_words.keys():
            num_words[word] += 1
        else:
            num_words[word] = 1
    return num_words

This worked for me

the for loop iterates through the list of words

the if statement checks to see if the word is in the dictionary: if it is, it adds 1 to the value at that key

if not, it adds the word to the dict and sets the value to 1

Nikola Jankovic
Nikola Jankovic
10,793 Points

I have manage to solve this thanks:

def word_count(string):
    list1 = string.lower().split()
    new_dict = {}
    number_count = 1
    for x in list1:
        if x in new_dict:
            number_count =  list1.count(x)
        else:
            number_count = 1

        new_dict.update({"{}".format(x): number_count})

    print(new_dict)