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

Hasan Jafri
Hasan Jafri
2,859 Points

Is there a better way? (improving my solution)

I recently completed the Word count dictionary challenge but know my code is not written in the best possible way for this challenge:

this is how it looks: def word_count(string): lower_case = string.lower().split() d={} for letter in lower_case: d[letter] = 0 for letter in lower_case: d[letter] += 1 return d

I was wondering if I could get some ideas on a better way to resolve the challenge

1 Answer

Hi, Hasan Here's one way to solve it:

def word_count(astring):
    results = {}
    alist = astring.lower().split()
    for item in alist:
        mycount = alist.count(item)
        results[item] = mycount  #could also use "results.update({item: mycount})"
    return results

Also, a helpful hint that I had to figure out the hard way, if you type ``` before and after the code you paste in, it shows up in a block (like above) and makes it easier for people to read. Hope this helps! D.