[FRPythoneers] sorting a list of dictionaries

Andrew Diederich diederic at boulder.net
Tue Jan 21 09:33:00 MST 2003


Excellent.  That did the trick.  I sorted on cn instead of sn, givenName,
since that's how we sort lists around here.  I'll throw my script at the
bottom of the message for those who are interested.  Python is cool.

I used Jack's cmp solution since that way I don't have to modify the list
again to remove the [0] element. The last name coincidence has nothing to
do with it.  :)

-- 
Andrew

 On Tue, 21 Jan 2003, Jack Diederich wrote:

> If 'exchangelist' is a list of tuples, the following will sort it with
> 'sn' as primary, and 'givenName' as secondary.
> 
> def mysort(a, b):
>   return cmp(a[1]['sn'], b[1]['sn']) or cmp(a[1]['givenName'], b[1]['givenName'])
> 
> exchangelist.sort(mysort)
> 
> 
> -jackdied
> _______________________________________________


#!/usr/bin/python
import ldap

print "Content-type: text/html"
print """

<HTML>
<HEAD>
<TITLE>Phone List</TITLE>
</HEAD>
<BODY>
"""

EXCHANGE_SERVER = "exchange.server.name"
# l = ldap.open("my_ldap_server.my_domain", ldap_port)
l = ldap.open(EXCHANGE_SERVER)
l.simple_bind_s("","")

# Full result set
res = l.search_s( "", ldap.SCOPE_SUBTREE,
"objectclass=organizationalperson")
l.unbind()

def mySort(a, b):
	return cmp(a[1]['cn'], b[1]['cn'])

res.sort(mySort)

print """
<table border="1">
<tr><td><strong>Name</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Email</strong></td>
<td><strong>Title</strong></td>
</tr>
"""

for user in res:
	D = user[1]
	if not D.has_key('telephoneNumber'): continue
	if not D.has_key('title'): D['title'] = " "
	if not D.has_key('mail'): D['mail'] = " "

# Below happens if a phone exists, but not a mail, and the has_key mail
thing
# isn't present
#Traceback (innermost last):
#  File "./debugphonebook.py", line 65, in ?
#    print '<td> %s </td>\n<td> %s </td>\n<td> %s </td>\n<td> %s
</td>\n</tr>\n' % (D['cn'][0], D['telephoneNumber'][0], D['mail'],
D['title'][0])
#KeyError: mail
# So that's why the above puts in a blank title or mail if none exists.

	print '<tr>'
	print '<td> %s </td>\n<td> %s </td>\n<td> %s </td>\n<td> %s
</td>\n</tr>\n' % (D['cn'][0], D['telephoneNumber'][0], D['mail'][0],
D['title'][0])

print "</TABLE>"
print "<P>"
"""

from normalDate import ND
today = ND()
print "Today's date: "
print today.formatUS()
print "</P>"

print "</BODY>"
print "</HTML>"





More information about the FRPythoneers mailing list