Mailing List Archive

Sorting tuples
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

Can somebody tell me what command will do this?

Jon Cosby
Sorting tuples [ In reply to ]
On Sun, 18 Apr 1999 14:57:52 -0700, Jon Cosby <jcosby@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@thecia.net, dfan@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/
Sorting tuples [ In reply to ]
> 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

Jon,

There are lots of cute ways to do this, and I
expect to see a bunch of followup posts that will
show off arcane Python wizardry, but the simple
solution is to use a dictionary.

The dictionary approach is quick, easy, and
more amenable to modification.

### Jon's list of tuples, shuffled
t = [ ('b','y','x'),
('a','v','w'),
('b','r','s'),
('c','u','t'),
('a','p','q'), ]

### build the dict
d = {}
for x in t:
if not d.has_key(x[0]):
d[x[0]] = []
for y in x[1:]:
d[x[0]].append(y)

### print the dict, sorting the values at the
### last possible moment.
keys = d.keys()
keys.sort()
for k in keys:
d[k].sort()
print k, ':', d[k]

It may not be obvious from the example above, but lists
of tuples can also just be sorted in place, e.g.

t = [ ('b','x','y'), ...
t.sort()

Python almost always follows the principle of least
surprise in this regard.

Best regards,

Jeff Bauer
Rubicon, Inc.