| 35 | next = __next__ |
| 36 | |
| 37 | class SortedDict(dict): |
| 38 | def __init__(self, mapping = {}, ignore_case = True, **kwargs): |
| 39 | """ |
| 40 | WARNING: SortedDict() with ignore_case==True will |
| 41 | drop entries differing only in capitalisation! |
| 42 | Eg: SortedDict({'auckland':1, 'Auckland':2}).keys() => ['Auckland'] |
| 43 | With ignore_case==False it's all right |
| 44 | """ |
| 45 | dict.__init__(self, mapping, **kwargs) |
| 46 | self.ignore_case = ignore_case |
| 47 | |
| 48 | def keys(self): |
| 49 | # TODO fix |
| 50 | # Probably not anymore memory efficient on python2 |
| 51 | # as now 2 copies of keys to sort them. |
| 52 | keys = dict.keys(self) |
| 53 | if self.ignore_case: |
| 54 | # Translation map |
| 55 | xlat_map = BidirMap() |
| 56 | for key in keys: |
| 57 | xlat_map[key.lower()] = key |
| 58 | # Lowercase keys |
| 59 | lc_keys = sorted(xlat_map.keys()) |
| 60 | return [xlat_map[k] for k in lc_keys] |
| 61 | else: |
| 62 | keys = sorted(keys) |
| 63 | return keys |
| 64 | |
| 65 | def __iter__(self): |
| 66 | return SortedDictIterator(self, self.keys()) |
| 67 | |
| 68 | def __reversed__(self): |
| 69 | return SortedDictIterator(self, self.keys(), reverse=True) |
| 70 | |
| 71 | def __getitem__(self, index): |
| 72 | """Override to support the "get_slice" for python3 """ |
| 73 | if isinstance(index, slice): |
| 74 | r = SortedDict(ignore_case = self.ignore_case) |
| 75 | for k in self.keys()[index]: |
| 76 | r[k] = self[k] |
| 77 | else: |
| 78 | r = super(SortedDict, self).__getitem__(index) |
| 79 | return r |
| 80 | |
| 81 | |
| 82 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected
searching dependent graphs…