[Tutor] sorting complicated lists

Michael P. Reilly arcege@shore.net
Fri, 23 Jun 2000 18:46:23 -0400 (EDT)


> 
> Hi everyone,
> 
> I'm working with python-ldap querying an ldap server to print employee phone
> directories, for example. Here's an example of the data structure that
> pyton-ldap returns using my record as an example (hope this wraps OK):
> 
> [('cn=WilsonT,ou=SIBLEY,o=ISD_197', {'revision': ['989'], 'givenName':
> ['Tim'], 'fullName': ['Tim Wilson'], 'mail': ['WilsonT@isd197.k12.mn.us'],
> 'postalCode': ['55118'], 'groupMembership':
> ['cn=Everyone,ou=SIBLEY,o=ISD_197', 'cn=GW52 Pilot,ou=SIBLEY,o=ISD_197',
> 'cn=TEACHERS PROGRAMS,ou=SIBLEY,o=ISD_197'], 'sn': ['Wilson'], 'street':
> ['1897 Delaware Avenue'], 'cn': ['WilsonT'], 'uid': ['WilsonT'], 'st':
> ['MN'], 'l': ['Sibley High School'], 'postalAddress': ['1897 Delaware
> Avenue$Mendota Heights$MN$55118'], 'objectClass': ['top', 'person',
> 'organizationalPerson', 'inetOrgPerson'], 'description': ['Sibley'],
> 'physicalDeliveryOfficeName': ['Mendota Heights'], 'telephoneNumber':
> ['405-2428']})]
> 
> You can see that the result is a list with containing 1 item. That item is a
> 2-element tuple with the first element my 'cn' and the second a dictionary
> containing all of the data in my ldap record.
> 
> If I retrieve 10 records, say, the list would consist of 10 tuples, one for
> each record retrieved. Now the question:
> 
> How would I sort the list so I could print the results of the ldap query in
> alphabetical order by surname? (That's the 'sn' key in the dictionary
> above.)

list.sort(lambda a, b: cmp(a[1]['sn'], b[1]['sn'])

a (or b)   = the tuple
a[1]       = the dictionary in the tuple
a[1]['sn'] = the 'sn' slot in the dictionary

References:  Language Reference, 2.1.5.2 Mutable Sequence Types
<URL:http://www.python.org/doc/current/lib/typesseq-strings.html#SECTION004152000000000000000>

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------