[Tutor] sorting lists in dictionary values

Eric Abrahamsen eric at abrahamsen.com
Sun Aug 26 11:43:32 CEST 2007


> From noob to noob : sort sorts in place. I seem to remember it  
> returns nothing.
>
> This works:
>
> In [12]: directoryOut[12]:
> {'A': ['Abercrombie', 'Aalberg'],
> 'B': ['Barnaby', 'Black', 'Biggles'],
> 'D': ['Douglas', 'Dawn', 'Diggle'],
> 'G': ['Granger', 'Gossen']}
>
> In [13]: for key in directory:
>    directory[key].sort()
>
> In [14]: directory
> Out[14]:
> {'A': ['Aalberg', 'Abercrombie'],
> 'B': ['Barnaby', 'Biggles', 'Black'],
> 'D': ['Dawn', 'Diggle', 'Douglas'],
> 'G': ['Gossen', 'Granger']}
>
> Please let me know if I'm wrong!
>
> Best
>
> Chris

Beautiful, that works perfectly. A single line added to the list  
comprehension:

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

and all is well.

Thanks for the help,
Eric



More information about the Tutor mailing list