Storing and Fetching

Step 2: Storing and Fetching

Now use the routing to actually store data. Each shard is its own little dict; a key only ever lives in the one shard that owns it.

  • put(key, value): store the pair in the key's shard
  • get(key): read the value from the key's shard, or None if it's not there
Hints
Starter code
class ShardedDB:
    def __init__(self, num_shards):
        self.num_shards = num_shards
        self.shards = [dict() for _ in range(num_shards)]

    def _hash(self, key):
        h = 0
        for ch in str(key):
            h = (h * 31 + ord(ch)) & 0xffffffff
        return h

    def _shard_for(self, key):
        return self._hash(key) % self.num_shards

    def put(self, key, value):
        """Store the pair in the shard that owns the key."""
        # TODO: self.shards[self._shard_for(key)][key] = value
        pass

    def get(self, key):
        """Fetch the value from the shard that owns the key, or None."""
        # TODO: return self.shards[self._shard_for(key)].get(key)
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.