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.

Easy Python 3.8+ Aug 9, 2026 AI & LLM integration patterns 12 views 0 copies

Python code

30 lines
Python 3.8+
facts = {}

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

stdout
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

  1. Use `defaultdict(dict)` from collections to simplify remember.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.