[Tutor] Re: Sorting dictionary values

Christopher Smith csmith@blakeschool.org
Thu, 16 Aug 2001 12:43:41 -0500


tutor@python.org writes:
>I suppose you could even make a general db sorter like this:
>
>def dbsort(key,db):
>  k=db.keys()
>  sort(lambda ki,defkey=key:db[ki][defkey],k)
>  return k

I noticed a lurking "shadow error" in my output window after sending this.
You can get rid of it by writing the following instead:

def dbsort(key,db):
	k=db.keys()
	sort(lambda ki,theKey=key,theDB=db: theDB[ki][theKey], k)
	return k

Note, too, that the function you provide to "sort" can do anything 
with that one argument--it is the return value that will be used
as the sorting criteria.

/c