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!

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

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.