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

Count word occurrences in a file & Sort them

I don't really know how to approach this task. I've managed to open a file, and get a list of all the words, but what if now i want to rank them and print out accordingly? What collection should i use? I thought of creating dicts like

{"word":how_many_times}

but that way i can't sort them. Or is it done by getting a list of tuples with

dict_like_above.items()

if so, how can i sort list of tuples by its first tuple items? Thanks a lot in advance for all explanations!

1 Answer

Steven Parker
Steven Parker
243,318 Points

You can sort a dictionary using the sorted() function.

The output will of course not be a dictionary itself, but a list.

for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)):
    print "%s: %s" % (key, value)

Thank you! Now, one more reason to dig into functional programming course to understand what lambda is =)