help printing dictionary, sorted by values.

Michael P. Reilly arcege at
Tue Aug 17 18:00:43 CEST 1999

Jerry Williams <jwilliam at> wrote:
: I have searched and searched the docs and am really frustrated with
: them.
: All I can seem to find is bits and pieces that hint about dictionaries.
: I finally found a table under mappings that listed the methods.  But
: I couldn't find anything that would list each data type and what methods
: are available.  What I am trying to do is take a file with a bunch of
: entries that appear more than once and list the count of each occurance
: in order of the highest count.  So if the file looked like:
: a
: a
: a
: b
: b
: c
: Then is would print:
: 3 a
: 2 b
: 1 c
: I thought a dictionary would work great, but can't seem to figure out
: how to sort it by values and also get the key.
: list = dict.values()
: list.sort()
: Then I get lost.  And the counts aren't going to be unique.
: Thanks for any help.  Please point me to where the methods are listed
: for
: the dictionary.  And some examples of dictionaries would be helpful.

How about:

  def repr_sorted_dict(d):
    """Return a string representation of a dictionary,
  sorted by value first."""
    def cmpitems_by_value(a, b):
      """sort first by second element in sequence."""
      v = cmp(a[1], b[1])
      # if equal, then sort by first element in sequence
      if v == 0:
        v = cmp(a[0], b[0])
      return v
    import string
    # retrieve the (key, value) pairs
    items = d.items()
    # display the pairs
    l = []
    for k, v in items:
      l.append("%s: %s" % (`k`, `v`))
    # now combine them as a dictionary display
    return '{' + string.joinfields(l, ', ') + '}'

Then you can:
  print repr_sorted_dict(my_values)

And if you really wanted to get fancy, you could make this function the
__repr__ method of a subclass of UserDict.UserDict.

  from UserDict import UserDict
  class ReverseSortedDict(UserDict):
    __repr__ = lambda self: repr_sorted_dict(

(Although I'd rewrite it to use the UserDict interface rather than itself, but that's just me. :)

Even if this is not exactly what you want, the "pairs = dict.items();
pairs.sort(...)" should get you where you are going. :)

This is documented at:


More information about the Python-list mailing list