Inserting Key-Value Pairs:
Now that we have a basic shell for our key-value store, let's add functionality to insert key-value pairs. Our method called insert
will take two arguments: a key
and a value
We'll implement this method by simply setting key
as a dictionary key and value
as its corresponding value. Think of the keys as being the registered names of NBA teams, and the values represent the full names of those teams. Here's how it might look:
1 def insert(self, key, value):
2 self.store[key] = value
With the above implementation, we can now add key-value pairs to our store like this:
1kvStore.insert('lakers', 'Los Angeles Lakers')
The insert
method sets 'lakers' as a key with the corresponding value 'Los Angeles Lakers'. Now when we print our key-value store, it would return:
1{'lakers': 'Los Angeles Lakers'}
As you can see, we've stored an NBA team's registered name and their full name in our key-value store. This is a simple functionality but forms the fundamental operation of our key-value store. It's similar to how insertion operations work in common Key-Values databases like Redis.
xxxxxxxxxx
class KeyValueStore:
def __init__(self):
self.store = {}
def insert(self, key, value):
self.store[key] = value
if __name__ == '__main__':
kvStore = KeyValueStore()
kvStore.insert('lakers', 'Los Angeles Lakers')
print('KeyValueStore with lakers Key:', kvStore.store)