[Tutor] sorting lists in dictionary values

Eric Abrahamsen eric at abrahamsen.com
Sun Aug 26 10:10:49 CEST 2007

I wrote the stupid little script below for practice; it takes a text  
file with a list of surnames, and returns a dictionary where the keys  
are first letters of the names, and the values are lists of names  
grouped under their appropriate first-letter key, like so:

{'A': ['Abercrombie'], 'B': ['Barnaby', 'Black', 'Biggles'], 'D':  
['Douglas', 'Dawn', 'Diggle'], 'G': ['Granger', 'Gossen']}

This is all well and good, but I want to sort the names in place, so  
that the names in each list are alphabetical. I tried slapping a sort 
() onto the dictionary list comprehension in every configuration I  
could think of. I even replaced the one-line comprehension with a two- 
step deal, like so:

for item in letters:
	little_list = [name for name in names if name.startswith(item)]
	phonebook[item] = little_list.sort()

That didn't work either, which I thought was very strange. Can anyone  

Another tangential question: why can't I do away with having a  
separate names = [] list variable, and write the comprehension as:

for item in letters:
	phonebook[item] = [line.strip('\n') for line in x if line.startswith 

Many thanks,

x = file('/path/to/file.txt', 'r')
letters = set()
names = []
phonebook = {}
for line in x:
	y = line[0].upper()
	names.append(line.strip('\n '))

for item in letters:
	phonebook[item] = [name for name in names if name.startswith(item)]

print phonebook
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070826/30ae9b10/attachment.htm 

More information about the Tutor mailing list