Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.