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

word_count not using list() function. What could be the problem?

I am using the list function to convert the string into a list. After some research online i found that I need to use split(). why do I need to use split? why won't this work with just a list() function?

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):
    str_list = list(string)
    str_dict = {}

    for word in str_list:
        if word.lower() in str_dict:
            str_dict[word.lower()] += 1
        else:
            str_dict[word.lower()] = 1 
    return str_dict

3 Answers

You can try the following example to show list includes whitespace.

>>> hi = 'hello world'
>>> hichars = list(hi)
>>> hichars
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] 
>>> ''.join(hichars)
'hello world'

One of the requirements of the challenge is to split on all whitespace.

Thanks

Steven Tagawa
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Steven Tagawa
Python Development Techdegree Graduate 14,438 Points

The short answer is, you're giving the computer way too much credit. There's nothing special in Python that tells the computer that your string is something called a "sentence" which is made of "words" which are separated by "spaces". The computer doesn't know any of these things. All it sees is a bunch of characters, so when you tell it to make a list from them, it does exactly what Kris showed: turn each character into its own item in the list.

Thanks, I understand it now

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

The str object has a build-in .split(arg) method, that will return a new list of substrings split from the original where ever an arg is found. If arg is omitted, then Whitespace is used to divide the string.

>>> hi = 'hello world'
>>> hiwords = hi.split()
>>> hiwords
['hello', 'world']

# for fun
>>> hiwords = hi.split('o')
>>> hiwords
['hell', ' w', 'rld']