Last active
April 20, 2017 01:02
-
-
Save kde713/3c442dd7118556ecefdb1a0a61ce66e7 to your computer and use it in GitHub Desktop.
Python Auto sorting objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
import operator | |
class SortedDict: | |
MESSAGE_TYPEERROR = "Only the int type can be used as the key of SortedDict." | |
MESSAGE_KEYERROR = "Key %d is not exist." | |
MESSAGE_VALUEERROR = "%s is not in dict." | |
def __init__(self, _dict=None): | |
self.keys = [] | |
self.values = [] | |
self.length = 0 | |
if _dict: | |
_dict = OrderedDict(sorted(_dict.items(), key=operator.itemgetter(0))) | |
for key in _dict.keys(): | |
if isinstance(key, int): | |
self.keys.append(key) | |
self.values.append(_dict[key]) | |
self.length += 1 | |
else: | |
raise TypeError(self.MESSAGE_TYPEERROR) | |
def __setitem__(self, key, value): | |
if isinstance(key, int): | |
try: | |
position = self.keys.index(key) | |
self.values[position] = value | |
except ValueError: | |
flag = False | |
for i in range(self.length): | |
if self.keys[i] > key: | |
flag = True | |
self.keys.insert(i, key) | |
self.values.insert(i, value) | |
break | |
if not flag: | |
self.keys.append(key) | |
self.values.append(value) | |
self.length += 1 | |
else: | |
raise TypeError(self.MESSAGE_TYPEERROR) | |
def __getitem__(self, key): | |
if isinstance(key, int): | |
try: | |
position = self.keys.index(key) | |
return self.values[position] | |
except ValueError: | |
raise KeyError(self.MESSAGE_KEYERROR % key) | |
else: | |
raise TypeError(self.MESSAGE_TYPEERROR) | |
def __delitem__(self, key): | |
if isinstance(key, int): | |
try: | |
position = self.keys.index(key) | |
del self.keys[position] | |
del self.values[position] | |
self.length -= 1 | |
except ValueError: | |
raise KeyError(self.MESSAGE_KEYERROR % key) | |
else: | |
raise TypeError(self.MESSAGE_TYPEERROR) | |
def __bool__(self): | |
return bool(self.keys) | |
def __str__(self): | |
_str = "{" | |
for i in range(self.length): | |
if i > 0: | |
_str += ", " | |
_str += "%d: %s" % (self.keys[i], repr(self.values[i])) | |
_str += "}" | |
return _str | |
def get(self, key): | |
try: | |
return self.__getitem__(key) | |
except KeyError: | |
return None | |
def keyofvalue(self, value): | |
try: | |
return self.keys[self.values.index(value)] | |
except ValueError: | |
raise ValueError(self.MESSAGE_VALUEERROR % str(value)) | |
def dict(self): | |
_dict = OrderedDict() | |
for i in range(self.length): | |
_dict[self.keys[i]] = self.values[i] | |
return _dict | |
if __name__ == "__main__": | |
# Init like OrderedDict | |
testdict = SortedDict({5: "test5", 1: "test1", 11: "test11", 12: "test12"}) | |
# Put like dict | |
testdict[5] = "new_test5" | |
testdict[1] = "new_test1" | |
testdict[3] = "new_test3" | |
testdict[25] = "new_test25" | |
testdict[7] = "new_test7" | |
# Delete like dict | |
del testdict[11] | |
# Get like dict | |
print(testdict[7]) | |
print(testdict.get(8)) | |
# You can also get key of value | |
print(testdict.keyofvalue("new_test5")) | |
# Print like dict | |
print(testdict) | |
# Use like Ordered dict with this method | |
print(testdict.dict()) | |
# You can get keys list and values list | |
print(testdict.keys) | |
print(testdict.values) | |
# You can get length of SortedDict without len() | |
print(testdict.length) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SortedList(list): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code has the same result and works more reliably.