python用字典实现字符表
实现功能有添加,查询,取出,清空,排序,大小,以及迭代功能:代码如下:
class StringTable(object):
def __init__(self):
self.string_set = {}
self._index = 0
def __str__(self):
# return '{}'.format(self.string_set)
return str(self.string_set)
def put(self, key, value):
self.string_set[key] = value
def get(self, key):
try:
return self.string_set[key]
except:
print('the key is wrong...')
def sort(self, reverse=False):
# ret = sorted(self.string_set.items(), key=lambda x: x[0])
self.string_set = {i[0]: i[1] for i in sorted(self.string_set.items(), key=lambda x: x[0], reverse=reverse)}
def size(self):
return len(self.string_set)
def pop(self, key):
ret = self.get(key)
del self.string_set[key]
return ret
def clear(self):
self.string_set = {}
def __iter__(self):
return self
def __next__(self):
if self._index < len(self.string_set):
key = list(self.string_set)[self._index]
val = self.string_set[key]
self._index += 1
return key, val
else:
raise StopIteration()
if __name__ == "__main__":
st = StringTable()
print(st)
st.put('h', 'dfa')
st.put('a', 'dafaf')
st.put('d', 'dsf')
st.put('p', 'fdafsa')
print(st)
st.sort(reverse=True)
print(st)
print('a:', st.get('a'))
print(st.pop('h'))
print(st)
for key, value in st:
print('key:', key, ',value:', value)
print(st.size())
st.clear()
print(st)