dm-tree: Nested Data Structure Utilities

0.1.10 · active · verified Thu Apr 09

dm-tree (DeepMind Tree) is a lightweight Python library designed for working with nested data structures such as lists, tuples, and dictionaries. It provides functional tools like `map_structure`, `flatten`, and `unflatten` to apply operations across arbitrary tree-like data. The current stable version is 0.1.10, and it follows an infrequent release cadence focused on stability for its core functionalities.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionalities of `dm-tree`: `map_structure` for applying a function to all 'leaf' elements, and `flatten`/`unflatten` for converting a nested structure into a flat list of elements and back again, preserving the original structure.

import tree

# Define a nested data structure
data_tree = {
    'a': [1, 2],
    'b': {'c': 3, 'd': (4, 5)},
    'e': 6
}

# 1. Map a function over all 'leaves' in the structure
def increment(x):
    return x + 1

mapped_tree = tree.map_structure(increment, data_tree)
print(f"Mapped tree: {mapped_tree}")
# Expected: {'a': [2, 3], 'b': {'c': 4, 'd': (5, 6)}, 'e': 7}

# 2. Flatten the structure into a list of leaves and a 'structure' object
leaves, structure = tree.flatten(data_tree)
print(f"Flattened leaves: {leaves}")
print(f"Original structure (abstracted): {structure}")
# Expected: Flattened leaves: [1, 2, 3, 4, 5, 6]

# 3. Unflatten the leaves back into the original structure
new_leaves = [x * 10 for x in leaves]
unflattened_tree = tree.unflatten(structure, new_leaves)
print(f"Unflattened tree: {unflattened_tree}")
# Expected: {'a': [10, 20], 'b': {'c': 30, 'd': (40, 50)}, 'e': 60}

view raw JSON →