Retrieving Values
Just as we have a method to insert key-value pairs into our store, we need a method to retrieve the values based on the keys. This is akin to asking, 'What's the full name of this NBA team given its registered name?'
To accomplish this, we'll add a method named retrieve
to our key-value store class. This method will accept a key
as an argument and return the corresponding value
. We'll use the get
method of the Python dictionary which allows us to fetch a value by its key. If the key is not found, get
would return None
, thus providing a level of error handling out of the box.
Here's how it might look:
1 def retrieve(self, key):
2 return self.store.get(key)
With the above implementation, we can now retrieve the full name of an NBA team given its registered name like this:
1print(kvStore.retrieve('lakers'))
Executing the above line would print 'Los Angeles Lakers' to the console.
This is an important operation for any key-value store as it enables us to access the stored data. It also aligns with the fundamental operation of retrieving data in common Key-Value databases like Redis.
xxxxxxxxxx
class KeyValueStore:
def __init__(self):
self.store = {}
def insert(self, key, value):
self.store[key] = value
def retrieve(self, key):
return self.store.get(key)
if __name__ == "__main__":
kvStore = KeyValueStore()
kvStore.insert('lakers', 'Los Angeles Lakers')
print(kvStore.retrieve('lakers'))
# Output: 'Los Angeles Lakers'