Updating Key-Value Pairs
If we recall from the previous screen, we created a retrieve
function to get the value for a given key from our key-value store. As an exercise, it would be a fun addition to allow updating these key-value pairs after their initial insertion too. In the spirit of datastores like Redis or MongoDB, we'd like to flexible in changing our data.
To modify the existing value of a key, we will add an update
method to our KeyValueStore class. This method will accept a key
and a value
as arguments. If the key
is already in the store, its value will be replaced with the new value
. Here's a sample implementation of the update
method:
1 def update(self, key, value):
2 if key in self.store:
3 self.store[key] = value
The function uses the key to check its availability in the store using the Python built-in in
keyword. If the key is present, it modifies the associated value.
To use our new update function, we'd do something similar to:
1kdStore.update('lakers', 'LA Lakers')
By executing the above line, it would update the value of 'lakers' in the dictionary to 'LA Lakers'. If you print the entire store, it should reflect this change.
Like we experienced with our implementation to retrieve values, it's rewarding to see our key-value store gaining some robust abilities, much like its real-world counterparts.
xxxxxxxxxx
if __name__ == '__main__':
class KeyValueStore:
def __init__(self):
self.store = {}
def insert(self, key, value):
self.store[key] = value
def update(self, key, value):
if key in self.store:
self.store[key] = value
kdStore = KeyValueStore()
kdStore.insert('lakers', 'Los Angeles Lakers')
print(kdStore.store)
kdStore.update('lakers', 'LA Lakers')
print(kdStore.store)