3
# This class functions almost exactly like UserDict. However, when using
4
# the sequence methods, it returns items in the same order in which they
5
# were added, instead of some random order.
7
# Copyright 2001 Adam Heath <doogie@debian.org>
9
# This file is free software; you can redistribute it and/or modify it
10
# under the terms of the GNU General Public License as published by
11
# the Free Software Foundation; either version 2 of the License, or
12
# (at your option) any later version.
14
# This program is distributed in the hope that it will be useful, but
15
# WITHOUT ANY WARRANTY; without even the implied warranty of
16
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17
# General Public License for more details.
19
# You should have received a copy of the GNU General Public License
20
# along with this program; if not, write to the Free Software
21
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
from UserDict import UserDict
25
class OrderedDict(UserDict):
28
def __init__(self, dict=None):
29
UserDict.__init__(self)
31
if dict is not None and dict.__class__ is not None:
34
def __cmp__(self, dict):
35
if isinstance(dict, OrderedDict):
36
ret=cmp(self.__order, dict.__order)
38
ret=UserDict.__cmp__(self, dict)
41
return UserDict.__cmp__(self, dict)
43
def __setitem__(self, key, value):
44
if not self.has_key(key):
45
self.__order.append(key)
46
UserDict.__setitem__(self, key, value)
48
def __delitem__(self, key):
50
del self.__order[self.__order.index(key)]
51
UserDict.__delitem__(self, key)
58
if self.__class__ is OrderedDict:
59
return OrderedDict(self)
61
return copy.copy(self)
67
return map(lambda x, self=self: (x, self.__getitem__(x)), self.__order)
70
return map(lambda x, self=self: self.__getitem__(x), self.__order)
72
def update(self, dict):
73
for k, v in dict.items():
74
self.__setitem__(k, v)