Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

3 matches
Dictionaries & sets medium

Find All Leaf Paths in a Nested Dict in Python

Recursively traverse a nested dictionary and yield every leaf path as a list of keys, including paths to empty dictionaries.

dictionary recursion nested-data
Python
def find_leaf_paths(data, path=None):
    if path is None:
        path = []
    
    if not isinstance(data, dict) or not data:
        yield path
        return
    
    for key, value in data.items():
        yield from find_leaf_paths(value, path + [key])

if __name__ == "__main__":
    nested = {
        "a": 1,
…
13 0 Open
Dictionaries & sets medium

How to Build a TTL Cache Dict in Python

Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.

dictionary cache ttl
Python
import time

class TTLDict(dict):
    def __init__(self, ttl, *args, **kwargs):
        self.ttl = ttl
        self._expires = {}
        super().__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._expires[key] = time.time() + self.ttl

    def __geti…
16 0 Open
Dictionaries & sets medium

How to Recursively Remove None Values from Nested Dictionaries in Python

Recursively removes all None values from nested dictionaries and lists while preserving non-None data.

dictionaries recursion data-cleaning
Python
def prune_none(obj):
    if isinstance(obj, dict):
        return {
            k: prune_none(v)
            for k, v in obj.items()
            if v is not None and prune_none(v) is not None
        }
    elif isinstance(obj, list):
        pruned = [prune_none(item) for item in obj]
        pruned = [item for item i…
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Dictionaries & sets — Python code examples

What you will find here

This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.