Sorting tuples

Dan Schmidt dfan at thecia.net
Sun Apr 18 20:28:33 EDT 1999


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/




More information about the Python-list mailing list