Back to index

plone3  3.1.7
odict.py
Go to the documentation of this file.
00001 # util.py
00002 # Copyright (C) 2005,2006 Michael Bayer mike_mp@zzzcomputing.com
00003 #
00004 # This module is part of SQLAlchemy and is released under
00005 # the MIT License: http://www.opensource.org/licenses/mit-license.php
00006 
00007 class OrderedDict(dict):
00008     """A Dictionary that returns keys/values/items in the order they were added"""
00009     def __init__(self, d=None, **kwargs):
00010         self._list = []
00011         self.update(d, **kwargs)
00012     def keys(self):
00013         return list(self._list)
00014     def clear(self):
00015         self._list = []
00016         dict.clear(self)
00017     def update(self, d=None, **kwargs):
00018         # d can be a dict or sequence of keys/values
00019         if d:
00020             if hasattr(d, 'iteritems'):
00021                 seq = d.iteritems()
00022             else:
00023                 seq = d
00024             for key, value in seq:
00025                 self.__setitem__(key, value)
00026         if kwargs:
00027             self.update(kwargs)
00028     def setdefault(self, key, value):
00029         if not self.has_key(key):
00030             self.__setitem__(key, value)
00031             return value
00032         else:
00033             return self.__getitem__(key)
00034     def values(self):
00035         return [self[key] for key in self._list]
00036     def __iter__(self):
00037         return iter(self._list)
00038     def itervalues(self):
00039         return iter([self[key] for key in self._list])
00040     def iterkeys(self): 
00041         return self.__iter__()
00042     def iteritems(self):
00043         return iter([(key, self[key]) for key in self.keys()])
00044     def __delitem__(self, key):
00045         try:
00046             del self._list[self._list.index(key)]
00047         except ValueError:
00048             raise KeyError(key)
00049         dict.__delitem__(self, key)
00050     def __setitem__(self, key, object):
00051         if not self.has_key(key):
00052             self._list.append(key)
00053         dict.__setitem__(self, key, object)
00054     def __getitem__(self, key):
00055         return dict.__getitem__(self, key)