I am trying to learn Python very well but I think I have miles to go before I can even say I am at the shore of the Pythonic Sea. I couldn’t think how to use get and set methods in Python for an in-memory key:value data store. My confusion came from “how do I use the Python dictionary?“
# Declare a class to store key, value pairs
class kv:
def __init__(self, k=None, v=None):
# Using the dictionary data type like so.
# When this class is called, you're creating
# a dictionary object.
self.store = {k : v}
def set(self, k, v):
self.store[k] = v
def get(self, k):
return self.store[k]
Example usage:
# Create a new kv object
new_kv = kv("a", "apple")
# OR you can even do: new_kv = kv()
# Set a key with a value
new_kv.set("b", "ball")
# Check if it worked
print(new_kv.get("b"))
----------------------------
# stdout
ball