~/problems / Stateful stores / In-memory database

Basics: records of fields in nested dicts

easy basics ~10 min

Every in-memory-database OA starts from the same data model: a record named by a string key, holding fields that map to string values. Build RecordStore with:

  • set(key, field, value) -> None: write the field, creating the record if it doesn't exist yet. Overwrites an older value.
  • get(key, field) -> str | None: the value, or None if the record or the field is missing. It must never raise, and it must not create anything.
  • delete(key, field) -> bool: remove the field and return True, or return False if it wasn't there. When a record loses its last field, the record itself is gone.
  • fields(key) -> list[str]: the field names of the record, sorted; [] for a missing record.
  • count() -> int: how many records currently exist (records with at least one field).
s = RecordStore()
s.set("user1", "name", "Ann")
s.set("user1", "city", "Oslo")
s.get("user1", "name")      # "Ann"
s.get("user2", "name")      # None
s.fields("user1")           # ["city", "name"]
s.delete("user1", "name")   # True
s.delete("user1", "name")   # False
s.delete("user1", "city")   # True
s.count()                   # 0: user1 has no fields left
Show hint

use a dict of dicts (key -> {field: value}), read with .get(...) so a missing key gives a default instead of a KeyError, and delete the inner dict when it becomes empty.

Topic: In-memory database. CRUD with fields, range scans, TTL expiry, time-travel reads.

0:00
Ctrl ' run · Ctrl ↵ submit
esc