Skip to content

Tree with Nested Dictionaries

Zero-dependency Python snippets for representing and manipulating trees using nested dictionaries.

4 snippets available in this sub-category.


Simple

Create a tree with nested dicts

tree dict nested data-structures

Represent a tree structure with nested dictionaries

tree = {"A": {"B": {}, "C": {"D": {}, "E": {}}}}
print(tree)
# {'A': {'B': {}, 'C': {'D': {}, 'E': {}}}}

Notes

  • Each key is a node; value is a dict of children
  • Leaves have empty dicts

Add a child node

tree add child dict data-structures

Add a child node to a given parent

def add_child(tree, parent, child):
    if parent in tree:
        tree[parent][child] = {}
    else:
        for node in tree.values():
            add_child(node, parent, child)


tree = {"A": {"B": {}, "C": {}}}
add_child(tree, "C", "D")
print(tree)
# {'A': {'B': {}, 'C': {'D': {}}}}

Notes

  • Recursively searches for parent
  • Adds child as empty dict

Remove a node

tree remove node dict data-structures

Remove a node (and its subtree) from the tree

def remove_node(tree, target):
    keys_to_remove = [k for k in tree if k == target]
    for k in keys_to_remove:
        del tree[k]
    for child in tree.values():
        remove_node(child, target)


tree = {"A": {"B": {}, "C": {"D": {}}}}
remove_node(tree, "C")
print(tree)
# {'A': {'B': {}}}

Notes

  • Recursively deletes all matching nodes

Complex

Traverse all nodes (preorder)

tree traverse preorder dict data-structures

Preorder traversal of all nodes

def traverse_preorder(tree):
    for node, children in tree.items():
        print(node)
        traverse_preorder(children)


tree = {"A": {"B": {}, "C": {"D": {}, "E": {}}}}
traverse_preorder(tree)
# A B C D E

Notes

  • Visits node, then children recursively

🔗 Cross Reference

🏷️ Tags

tree, dict, nested, add, remove, traverse, leaf, print, data-structures

📝 Notes

  • Nested dicts are a flexible way to represent trees in Python
  • For large or complex trees, consider custom classes or third-party libraries