[Tutor] Second problem

David Ascher da@ski.org
Sun, 13 Jun 1999 13:08:37 -0700 (Pacific Daylight Time)


On Sun, 13 Jun 1999, Jon Cosby wrote:

> Another problem: The following prints out keys and values multiple times,
> once for each key with the same value; if three keys have the same value, it
> will print each three times. Is there some condition I can add to prevent
> this?

> keys = dict.keys()
> vals = dict.values()
> vals.sort(comp)
> for v in vals:
>     for k in keys:
>         if dict[k] == v:
>            print k, v  # for simplicity

What I'd do is to sort on the items with a custom sort which did the
equivalent of sorting on keys:

def sort_items((k1,v1), (k2,v2)):
  return cmp(v1, v2)  # sort on values

# or written just slightly differently, but equivalently
# def sort_items(a, b):
#   return cmp(a[1], b[1])  # sort on values

items = dict.items()
items.sort(sort_items)
for key, value in items:
   print key, value  # or whatever

Cheers,

--david