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

Why does this not pass but gives different ordered, but correct results?

I've read this threat, which is explaining why it didn't pass but I still don't understand why.

I used the following code

def word_count(arg):
    words = arg.lower().split(" ")
    words_dict = {}

    for word in words:
        if word in words_dict:
            words_dict[word] += 1
        else:
            words_dict[word] = 1

    return words_dict

The mentioned thread says that it does not split properly if there is a trailing whitespace, which, in theory makes sense. It seems like an edgecase, though.

Theoretically it should of passed but it did not give me an error that stated that there was something wrong with the method, but referenced that the output was not what was expected and suggested I use .lower()

Also, using:

words = arg.lower().split()

instead of :

words = arg.lower().split(" ")

returns the same dictionary, but with a different order.

Why doesn't .split() split every character instead of at spaces when you are not providing an argument?

Also, shouldn't the test have passed? Maybe shouldn't the error given more reflect the issue? possibly something about length of the obj being too long/too short, empty key or ect.?

1 Answer

Just for your reference, dictionaries don't have order. The order is random. That's why

words = arg.lower().split()

And

words = arg.lower().split(" ")

Return the same dictionary in a different order.