faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 9 people (56%) answered Yes
Recently 2 of 6 people (33%) answered Yes

Entry

Sorted dictionary (was: Alphabetized dictionary listings)

Aug 9th, 2008 02:12
Sek Tea, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 323, Jeff Epler


"""
Packages: basic_datatypes.dictionaries
"""
"""
>Why does this occur? More to the point, how can I have the print-out
>be in alphabetical order?
The FAQ gives a __repr__ method; you probably want __str__ to do the same
thing.  Here are implementations of .items() and .keys() (what do you want
for .values()?:
"""
from UserDict import UserDict
class SortedDict(UserDict):
	def keys(self):
		l = self.data.keys()
		l.sort()
		return l
	def items(self):
		l = self.data.items()
		l.sort()
		return l
names = ["Bob", "Larry", "Curly", "Moe", "Jeff", "Guido", "Parrot"]
dict  = SortedDict()
for name in names:
	dict[name] = len(name)
for i,j in dict.items():
	print "%s's name is %d letters long" % (i,j)
http://regalos-de-navidad.blogspot.com/
http://regalosdesanvalentin.blogspot.com/
http://ideas-para-regalar.blogspot.com/