[Newbie] How to output dictionary sorted on content (not keys)

Boudewijn Rempt boud at valdyas.org
Thu Jul 4 08:40:39 EDT 2002


Ben Fairbank wrote:

> I have several long (thousands of entries) dictionaries of words used
> in plays; associated with each word is the number of times it is used
> in the play.  I have had no problem printing the words alphabetically
> (send keys to a list, sort the list, access dictionary by the sorted
> key list), but I have not found an elegant way to sort by  frequency
> of use.  The best I have been able to do is a workable but inelegant
> kluge that looks more like Basic than Python.  Is there a "Python Way"
> of doing that?
> 

Well, basically you have table with two columns: word and frequency. 
Python's dictionary provides for only one index, on the first column. 
If you want to use the second column, you'll have to invert the dictionary,
making it one mapping words on frequencies. That's always going to take
some time. You might do something like:

w2f={'a': 2,
     'b': 2,
     'c': 1,
     'd': 3,
     'e': 3}

f2w={}

for k, v in w2f.items():
  if f2w.has_key(v):
    f2w[v].append(k)
  else:
    f2w[v]=[k]

print f2w

{1: ['c'], 2: ['a', 'b'], 3: ['e', 'd']}

No doubt more elegant solutions exist, and it would be best to fill both 
dictionaries at the same time.

-- 
Boudewijn Rempt | http://www.valdyas.org



More information about the Python-list mailing list