|
1
|
When you write a directory for a group of people, you want it grouped by last name initial and then sorted alphabetically. This recipe does just that; it creates a dictionary keyed by last name initial with a value of a tuple of names sorted in alphabetical order. The input to 'groupnames' should be an iterable that returns strings that contain names written in first-middle-last fashion with each part separated by whitespace. The resulting names in the grouped dict will have normalized whitespace.
This recipe uses several new features in Python 2.4 . One is the built-in 'sorted' which takes in an iterable and returns a new list of the items returned from the iterable sorted. It also uses a key function for the sort which is new functionality also for list.sort that for using the DSU (Decorate-Sort-Undecorate) idiom without having to do the decoration ahead of time. Lastly, the itertools module's new 'groupby' function is used to separate out the names based on last name initial. It also uses doctest for testing which for Python 2.4 has been thoroughly refactored and rewritten. Possible improvements is forcing all parts of the name to be capitalized properly (easy using str.capitalize) and not assuming everyone has a last name.
Tags: search
|
1 comment
Add a comment
Sign in to comment

Download
Copy to clipboard
