PYTHON
Representing Hierarchical Data (Trees)
Learn to model hierarchical data structures like file systems or nested comments using Python dictionaries and lists, crucial for web data representation.
# Example: Representing a file system directory structure
file_system_tree = {
"name": "root",
"type": "directory",
"children": [
{
"name": "home",
"type": "directory",
"children": [
{"name": "user", "type": "directory", "children": []},
{"name": "documents", "type": "directory", "children": [
{"name": "report.pdf", "type": "file"},
{"name": "notes.txt", "type": "file"}
]},
],
},
{
"name": "var",
"type": "directory",
"children": [
{"name": "log", "type": "directory", "children": []}
],
},
{"name": "README.md", "type": "file"},
],
}
def print_tree(node, indent=0):
prefix = " " * indent
print(f"{prefix}- {node['name']} ({node['type']})")
if "children" in node:
for child in node["children"]:
print_tree(child, indent + 1)
print("File System Structure:")
print_tree(file_system_tree)
# Another example: Nested comments on a post
comments_tree = [
{
"id": 1,
"author": "Alice",
"text": "Great post!",
"replies": [
{
"id": 2,
"author": "Bob",
"text": "I agree!",
"replies": []
},
{
"id": 3,
"author": "Charlie",
"text": "Very insightful.",
"replies": [
{
"id": 4,
"author": "David",
"text": "Thanks Charlie!",
"replies": []
}
]
}
]
},
{
"id": 5,
"author": "Eve",
"text": "Interesting perspective.",
"replies": []
}
]
print("
Nested Comments:")
def print_comments(comments, indent=0):
for comment in comments:
prefix = " " * indent
print(f"{prefix}- {comment['author']}: {comment['text']}")
if comment['replies']:
print_comments(comment['replies'], indent + 1)
print_comments(comments_tree)
How it works: Hierarchical data, often resembling a tree structure, is ubiquitous in web development (e.g., file systems, categories, nested comments, JSON API responses). Python's dictionaries and lists are perfectly suited to represent such data. A common pattern involves a dictionary for a node's properties (like `name`, `type`, `id`, `author`, `text`) and a list for its `children` or `replies`. This allows for flexible and deeply nested structures, which can be easily traversed and manipulated using recursion or iteration.