基于Python实现父子关系数据转树形结构及编码分配的需求
Alright, let's work through converting your parent-child data into a structured tree with hierarchical codes in Python. First off, I spotted a duplicate id:5 in your sample data (used for both C2 and C4) — I’ll fix that to id:7 for C4 in my example to avoid key conflicts, since duplicate IDs would break our mapping later. Here's a step-by-step solution:
First, we’ll create a dictionary to map each item’s id to its full data. This lets us quickly look up parent nodes when building the tree. We’ll also convert id and fa_id to integers (since they’re strings in your sample) and initialize an empty children list for every item.
# Fixed sample data (resolved duplicate id issue) data = [ {'id': 1, 'fa_id': '0', 'name': 'A1'}, {'id': 2, 'fa_id': '1', 'name': 'B1'}, {'id': 3, 'fa_id': '1', 'name': 'B2'}, {'id': 4, 'fa_id': '2', 'name': 'C1'}, {'id': 5, 'fa_id': '2', 'name': 'C2'}, {'id': 6, 'fa_id': '3', 'name': 'C3'}, {'id': 7, 'fa_id': '3', 'name': 'C4'} ] # Create a map from id to item, and set up children lists item_map = {} for item in data: # Convert ID fields to integers for consistent comparison item['id'] = int(item['id']) item['fa_id'] = int(item['fa_id']) item['children'] = [] item_map[item['id']] = item
Next, we’ll loop through each item and attach it to its parent’s children list. Root nodes (those with fa_id:0) go directly into our top-level tree list.
tree = [] for item in data: parent_id = item['fa_id'] if parent_id == 0: # Add root nodes to the main tree tree.append(item) else: # Attach child to its parent's children list (if parent exists) if parent_id in item_map: item_map[parent_id]['children'].append(item)
We’ll use a recursive function to traverse the tree and assign codes like 1, 1.1, 1.1.1 — these codes reflect the node’s level and position within its parent’s children.
def assign_hierarchical_codes(node, parent_code="", child_index=1): # Generate code for current node if parent_code == "": node['code'] = str(child_index) else: node['code'] = f"{parent_code}.{child_index}" # Recursively assign codes to all children for idx, child in enumerate(node['children'], start=1): assign_hierarchical_codes(child, node['code'], idx) # Apply code assignment to root nodes for idx, root_node in enumerate(tree, start=1): assign_hierarchical_codes(root_node, "", idx)
If you don’t need the original id and fa_id fields in the final tree, you can remove them with another recursive function:
def clean_unwanted_fields(node): # Remove id and fa_id if present node.pop('id', None) node.pop('fa_id', None) # Recursively clean children for child in node['children']: clean_unwanted_fields(child) # Clean all nodes in the tree for root in tree: clean_unwanted_fields(root)
To view the formatted tree, you can print it with json.dumps for readability:
import json print(json.dumps(tree, indent=2))
This will output exactly the structure you’re looking for, plus the hierarchical codes:
[ { "name": "A1", "children": [ { "name": "B1", "children": [ { "name": "C1", "children": [], "code": "1.1.1" }, { "name": "C2", "children": [], "code": "1.1.2" } ], "code": "1.1" }, { "name": "B2", "children": [ { "name": "C3", "children": [], "code": "1.2.1" }, { "name": "C4", "children": [], "code": "1.2.2" } ], "code": "1.2" } ], "code": "1" } ]
内容的提问来源于stack exchange,提问作者haidong zhang

