Skip to content

Instantly share code, notes, and snippets.

@kde713
Last active April 20, 2017 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kde713/3c442dd7118556ecefdb1a0a61ce66e7 to your computer and use it in GitHub Desktop.
Save kde713/3c442dd7118556ecefdb1a0a61ce66e7 to your computer and use it in GitHub Desktop.
Python Auto sorting objects
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)
class SortedList(list):
pass
@2minchul
Copy link

2minchul commented Apr 20, 2017

This code has the same result and works more reliably.

    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

@kde713
Copy link
Author

kde713 commented Apr 20, 2017

@2minchul Thanks for tip. I applied it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment