By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,404 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,404 IT Pros & Developers. It's quick & easy.

sorting a dictionary?

P: n/a
I have a dictionary which contains some words and
their frequency in a short novel.

It looks like this:

mydict = {'the':358, 'they':29, 'went':7, 'said':65}

Is there an easy to sort this dictionary and get a
list like the following (in decreasing order)?

the 358
said 65
they 29
went 7

Thanks
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
This comes up so often on this list that there are many examples and
recipes.
You are looking for a dictionary sort by value.
search strategy:
Python sorting dictionary

44,000+ hits on google.
First entry:
http://aspn.activestate.com/ASPN/Pyt...k/Recipe/52306

hth,
M.E.Farmer

Jul 18 '05 #2

P: n/a
Anthony Liu wrote:
mydict = {'the':358, 'they':29, 'went':7, 'said':65}
Is there an easy to sort this dictionary and get a
list like the following (in decreasing order)?

Yes.

def sortkey((word, frequency)):
return -frequency, word

for word_freq in sorted(mydict.items(), key=sortkey):
print '%-6s %s' % word_freq
--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.