[Tutor] sorting lists in dictionary values

Ricardo Aráoz ricaraoz at gmail.com
Sun Aug 26 14:03:42 CEST 2007


Eric Abrahamsen wrote:
> 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 help?
> 
> 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(item)]
> 
> 
> Many thanks,
> Eric
> 
> ================
> x = file('/path/to/file.txt', 'r')
> letters = set()
> names = []
> phonebook = {}
> for line in x:
> y = line[0].upper()
> letters.add(y)
> names.append(line.strip('\n '))
> 
> for item in letters:
> phonebook[item] = [name for name in names if name.startswith(item)]
> 
> print phonebook
> 
> ------------------------------------------------------------------------
>

Try this :

nameFile = open(r'/path/to/file.txt', 'rU')
phonebook = {}

for line in nameFile :
    phonebook.setdefault(line[0].upper(), []).append(line.strip('\n'))

for item, names in phonebook.iteritems() :
    names.sort()

print phonebook

HTH



More information about the Tutor mailing list