[Tutor] sorting lists in dictionary values
Eric Abrahamsen
eric at abrahamsen.com
Sun Aug 26 16:50:12 CEST 2007
Whoa, this made my brain hurt. And I thought I was being clever using
a set...
I can't say I really understand this yet, but I'm trying. If anyone's
following along at home I found this link kind of helpful:
http://python.net/crew/mwh/hacks/setdefault.html
Thanks a lot for your help,
Eric
> 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