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

Help Please. It's the second time I ask

I want to create a dict from two lists, but I can't. Help

wordcount.py
def word_count(string):
    list_1 = string.lower().split()
    for item in list_1:
        list_2 = list_1.count(item)
    my_dict = dict(zip(list_1, list_2))
    return my_dict

1 Answer

Hi, I'm just a student like you so there might be a better way to do this. Here's what I did:

def word_count(my_string):
    # convert the string to lower case
    my_string = my_string.lower()

    # convert the string to a list
    my_list = my_string.split()

    # count the words and create the dictionary
    # key = word in list
    # value = times word appears
    my_dict = {}
    for i in my_list:
        word_count = my_list.count(i)
        my_dict.update({i:word_count})
    return my_dict

I like to make the comments first then fill it out with the code. Good luck on your quest.