sorting a dictionary?

A

Anthony Liu

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
 
S

Scott David Daniels

Anthony said:
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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,222
Messages
2,571,142
Members
47,775
Latest member
MadgeMatti

Latest Threads

Top