S3/SortedDict.py
ec50b5a7
 ## Amazon S3 manager
 ## Author: Michal Ludvig <michal@logix.cz>
 ##         http://www.logix.cz/michal
 ## License: GPL Version 2
 
29941bdf
 from BidirMap import BidirMap
 
ec50b5a7
 class SortedDictIterator(object):
29941bdf
 	def __init__(self, sorted_dict, keys):
 		self.sorted_dict = sorted_dict
 		self.keys = keys
df9fa4b5
 
 	def next(self):
29941bdf
 		try:
 			return self.keys.pop(0)
 		except IndexError:
df9fa4b5
 			raise StopIteration
 
 class SortedDict(dict):
29941bdf
 	keys_sort_lowercase = True
df9fa4b5
 
 	def keys(self):
 		keys = dict.keys(self)
29941bdf
 		if self.keys_sort_lowercase:
 			# Translation map
 			xlat_map = BidirMap()
 			for key in keys:
 				xlat_map[key.lower()] = key
 			# Lowercase keys
 			lc_keys = xlat_map.keys()
 			lc_keys.sort()
 			return [xlat_map[k] for k in lc_keys]
 		else:
 			keys.sort()
 			return keys
df9fa4b5
 
29941bdf
 	def __iter__(self):
 		return SortedDictIterator(self, self.keys())
 
 if __name__ == "__main__":
 	d = SortedDict()
 	d['AWS'] = 1
 	d['Action'] = 2
 	d['america'] = 3
 	d.keys_sort_lowercase = True
 	print "Wanted: Action, america, AWS,"
 	print "Got:   ",
 	for key in d:
 		print "%s," % key,
 	print "   __iter__()"
 	d.keys_return_lowercase = True
 	print "Got:   ",
 	for key in d.keys():
 		print "%s," % key,
 	print "   keys()"