[Tutor] sorting lists in dictionary values

Terry Carroll carroll at tjc.com
Mon Aug 27 01:07:01 CEST 2007


On Sun, 26 Aug 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. 

You want sorted(), not sort():


>>> names = ['Abercrombie', 'Barnaby', 'Douglas', 'Granger', 'Black', 
'Dawn','Gssen', 'Biggles', 'Diggle']
>>> from string import uppercase as letters
>>> mydict={}
>>> for letter in letters:
...  mydict[letter] = sorted([name for name in names if name.startswith(letter))
...
>>> mydict
{'A': ['Abercrombie'], 'C': [], 'B': ['Barnaby', 'Biggles', 'Black'], 'E': [],
D': ['Dawn', 'Diggle', 'Douglas'], 'G': ['Gossen', 'Granger'], 'F': [], 
'I': [] 'H': [], 'K': [], 'J': [], 'M': [], 'L': [], 'O': [], 'N': [], 
'Q': [], 'P': [, 'S': [], 'R': [], 'U': [], 'T': [], 'W': [], 'V': [], 
'Y': [], 'X': [], 'Z':]}
>>>

You can get rid of the empties...

>>> for key in mydict.keys():   #Note: not "for key in mydict:"
...  if mydict[key] == []: del mydict[key]
...
>>> mydict
{'A': ['Abercrombie'], 'B': ['Barnaby', 'Biggles', 'Black'], 'D': ['Dawn', 
'Diggle', 'Douglas'], 'G': ['Gossen', 'Granger']}



More information about the Tutor mailing list