Fixed #3993 -- Added some useful dictionary methods to SortedDict, plus an insert() method. Patch from Paul Collier.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@6350 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Malcolm Tredinnick 2007-09-16 03:27:38 +00:00
parent 8ccf2028c2
commit ec7d80b9dd
2 changed files with 21 additions and 0 deletions

View File

@ -83,6 +83,7 @@ answer newbie questions, and generally made Django that much better:
Russell Cloran <russell@rucus.net> Russell Cloran <russell@rucus.net>
colin@owlfish.com colin@owlfish.com
crankycoder@gmail.com crankycoder@gmail.com
Paul Collier <paul@paul-collier.com>
Pete Crosier <pete.crosier@gmail.com> Pete Crosier <pete.crosier@gmail.com>
Matt Croydon <http://www.postneo.com/> Matt Croydon <http://www.postneo.com/>
flavio.curella@gmail.com flavio.curella@gmail.com

View File

@ -72,12 +72,23 @@ class SortedDict(dict):
def items(self): def items(self):
return zip(self.keyOrder, self.values()) return zip(self.keyOrder, self.values())
def iteritems(self):
for key in self.keyOrder:
yield key, dict.__getitem__(self, key)
def keys(self): def keys(self):
return self.keyOrder[:] return self.keyOrder[:]
def iterkeys(self):
return iter(self.keyOrder)
def values(self): def values(self):
return [dict.__getitem__(self, k) for k in self.keyOrder] return [dict.__getitem__(self, k) for k in self.keyOrder]
def itervalues(self):
for key in self.keyOrder:
yield dict.__getitem__(self, key)
def update(self, dict): def update(self, dict):
for k, v in dict.items(): for k, v in dict.items():
self.__setitem__(k, v) self.__setitem__(k, v)
@ -91,6 +102,15 @@ class SortedDict(dict):
"Returns the value of the item at the given zero-based index." "Returns the value of the item at the given zero-based index."
return self[self.keyOrder[index]] return self[self.keyOrder[index]]
def insert(self, index, key, value):
"Inserts the key, value pair before the item with the given index."
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index: index -= 1
self.keyOrder.insert(index, key)
dict.__setitem__(self, key, value)
def copy(self): def copy(self):
"Returns a copy of this object." "Returns a copy of this object."
# This way of initializing the copy means it works for subclasses, too. # This way of initializing the copy means it works for subclasses, too.