Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

3 matches
Dictionaries & sets medium

Unflatten Dot Keys to Nested Dict in Python

Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.

dictionaries nested flatten
Python
def unflatten_dot_keys(flat_dict):
    result = {}
    for flat_key, value in flat_dict.items():
        parts = flat_key.split(".")
        current = result
        for part in parts[:-1]:
            current = current.setdefault(part, {})
        current[parts[-1]] = value
    return result


if __name__ == "__main_…
14 0 Open
AI & LLM integration patterns medium

How to Build a Data Helper for LLM Prompts in Python

A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.

llm prompt-engineering data-prep
Python
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Simple helper class for working with data in AI/LLM pipelines."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
        self.data = data or {}
    
    def flatten(self, prefix: str = "") -> Dict[str, Any]…
17 0 Open
Database scaling & optimization medium

Simulate a GIN Index for JSONB in Python

Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.

jsonb gin-index inverted-index
Python
import json
import random
from collections import defaultdict

# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
    def __init__(self):
        self.posting_lists = defaultdict(list)  # token -> list of doc_ids
    
    def index(self, doc_id, json_obj):
        """Index a JSON documen…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.