How to Build an Entity Memory Dict to Store Facts in Python
Store and recall facts about entities using nested dictionaries with remember, recall, and forget functions in Python.
Python code
30 linesfacts = {}
def remember(entity, attribute, value):
if entity not in facts:
facts[entity] = {}
facts[entity][attribute] = value
def recall(entity, attribute):
return facts.get(entity, {}).get(attribute, None)
def forget(entity, attribute=None):
if attribute is None:
facts.pop(entity, None)
else:
facts.get(entity, {}).pop(attribute, None)
if __name__ == "__main__":
remember("alice", "age", 30)
remember("alice", "city", "paris")
remember("bob", "age", 25)
print(recall("alice", "age"))
print(recall("alice", "city"))
print(recall("bob", "unknown"))
forget("alice", "city")
print(recall("alice", "city"))
forget("bob")
print(facts)
Output
30
paris
None
None
{}
How it works
The code uses a nested dictionary where the outer keys are entity names and the inner keys are attribute names. remember creates a new inner dict if the entity is new, then sets the attribute. recall uses .get() with default empty dicts to safely handle missing entities and attributes. forget removes an attribute or an entire entity, using .pop() with defaults to avoid errors. The if __name__ == "__main__" guard ensures the demo only runs when the script is executed directly, not when imported.
Common mistakes
- Forgetting to initialize the inner dict for a new entity, causing a KeyError.
- Using `recall` without default values when the entity doesn't exist.
- Assuming `recall` raises an error for missing keys, but it should return None.
Variations
- Use `defaultdict(dict)` from collections to simplify remember.
- Use external libraries like chromadb or faiss for persistent vector memory.
Real-world use cases
- Storing conversation context per user in a chatbot to personalize responses.
- Caching user preferences in a lightweight in-memory store for session data.
- Tracking state of entities like orders or devices in a simple task automation script.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.