1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class ListOrderedDict(OrderedDict): def __getitem__(self, key): if is_integer(key): key = list(self.keys())[key] elif isinstance(key, slice): slicedkeys = list(self.keys())[key] lod_obj = type(self)() for slicedkey in slicedkeys: lod_obj[slicedkey] = self[slicedkey] return lod_obj return super().__getitem__(key)
def append(self, key, value): if is_integer(key): raise RuntimeError(f" integer key is not allowed in ListOrderedDict {key}.") assert key not in self, f"cannot add existed key. {key}" self[key] = value def __setitem__(self, key, value): 'od.__setitem__(i, y) <==> od[i]=y' if is_integer(key): raise RuntimeError(f" integer key is not allowed in ListOrderedDict {key}.") else: return super().__setitem__(key, value)
def __delitem__(self, key): 'od.__delitem__(y) <==> del od[y]' if is_integer(key): key = list(self.keys())[key]
return super().__delitem__(key)
def move_to_end(self, key, last=True): '''Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist. ''' if is_integer(key): key = list(self.keys())[key]
return super().move_to_end(key, last)
def __repr__(self): 'od.__repr__() <==> repr(od)' if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self.items()))
def pop(self, key=-1): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if is_integer(key): if len(list(self.keys())) == 0: print(f"pop a None from an empty ListOrderedDict.") return None key = list(self.keys())[key] return super().pop(key)
def setdefault(self, key, default=None): '''Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default. ''' if is_integer(key): key = list(self.keys())[key] return super().setdefault(key, default)
|