faqts : Computers : Programming : Languages : Python : Snippets : Tuples

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

71 of 91 people (78%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Sorting tuples

Dec 12th, 2004 17:03
Hans Raaf, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 365, Jeff Bauer


"""
Packages: basic_datatypes.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
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 x[0] in d:
        d[x[0]]+=x[1:]
    else:
        d[x[0]]=x[1:]
### 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.
"""