""" dictionary.py This is take 1, without any collision checking or handling ... and so will sometimes do the wrong thing. >>> d = Dictionary() >>> d.set('name', 'Jim') >>> d.set('age', 59) >>> d.get('name') 'Jim' >>> d.get('haircolor') False >>> len(d) 2 """ def hash(key): """ Return a number ('the hash') of a key """ # This one was Cyrus' idea. keystring = str(key) result = '' for symbol in keystring: result += str(ord(symbol)) return int(result) class Dictionary: def __init__(self, size=100): self.table_size = size self.table = [None]*size self.n_entries = 0 def __len__(self): return self.n_entries def set(self, key, value): index = hash(key) % self.table_size self.table[index] = (key, value) self.n_entries += 1 def get(self, key, missing=False): index = hash(key) % self.table_size result = self.table[index] if result: return result[1] else: return missing if __name__ == '__main__': import doctest doctest.testmod()