From: dfan at thecia.net (Dan Schmidt)
Date: 19 Apr 1999 00:28:33 GMT
Subject: Sorting tuples
References: <7fdkhf$12d$1@sparky.wolfe.net>
Message-ID: <slrn7hktrf.2um.dfan@ppp39-170.thecia.net>
X-UID: 285                                                  

On Sun, 18 Apr 1999 14:57:52 -0700, Jon Cosby <jcosby at wolfenet.com> wrote:
| I have a list of tuples
| [('a','p','q'),('b','r','s'),('c','t','u'),('a','v','w'),('b','x','y')],
| and I want to print out
| 
| a : p, q, v, w
| b : r, s, x, y
| c : t, u

This works:

# Create a dictionary indexed by the first element of each tuple
tups = [('a','p','q'),('b','r','s'),('c','t','u'),('a','v','w'),('b','x','y')]
dict = {}
for tup in tups:
  key, val = tup[0], tup[1:]
  try:
    dict[key] = dict[key] + list(val)
  except KeyError:
    dict[key] = list(val)

import string
keys = dict.keys()
keys.sort()          # keys is now a sorted list of the keys in dict
for key in keys:
  print "%s : %s" % (key, string.join (dict[key], ", "))
  
-- 
                 Dan Schmidt -> dfan at thecia.net, dfan at alum.mit.edu
Honest Bob & the                http://www2.thecia.net/users/dfan/
Factory-to-Dealer Incentives -> http://www2.thecia.net/users/dfan/hbob/
          Gamelan Galak Tika -> http://web.mit.edu/galak-tika/www/




