1. 第一种(家族关系)
comment_list = [
{"id": 1, "name": "a", "content": "xx", "pid":None},
{"id": 2, "name": "a", "content": "xx", "pid":1},
{"id": 3, "name": "a", "content": "xx", "pid":1},
{"id": 4, "name": "a", "content": "xx", "pid":3},
]
comment_dict = {}
######### 家族树关系的构建 ############
# 1.循环初始数据 添加children 构造字典格式
for item in comment_list:
item["children"] = []
comment_dict[item["id"]] = item
# 2. 循环初数据 判断pid,如果有pid,添加到相应的父级
for row in comment_list:
if not row["pid"]:
continue
pid = row["pid"]
comment_dict[pid]["children"].append(row)
print(comment_dict)
2. 第二种(父子关系)
comment_list = [
{"id": 1, "name": "a", "content": "1"},
{"id": 2, "name": "a", "content": "2"},
{"id": 3, "name": "a", "content": "3"},
{"id": 4, "name": "a", "content": "4"},
]
son_list = [
{"id": 1, "name": "a1", "content": "1-1", "replay_id": 1,"depth": 2, "root": 1},
{"id": 2, "name": "a1", "content": "2-1", "replay_id": 2,"depth": 2, "root": 2},
{"id": 3, "name": "a1", "content": "3-1", "replay_id": 3,"depth": 2, "root": 3},
{"id": 4, "name": "a1", "content": "4-1", "replay_id": 4,"depth": 2, "root": 4},
{"id": 5, "name": "a1", "content": "4-2", "replay_id": 4,"depth": 2, "root": 4},
]
comment_dict = {}
######### 二级评论的处理 ############
# 1.循环初始数据 添加children 构造初始化字典格式
for item in comment_list:
item["children"] = []
comment_dict[item["id"]] = item
# 2. 循环二级评论 用replay_id,去初始化的字典里面,找到对应的父级,添加到children里面
for row in son_list:
replay_id = row["replay_id"]
if replay_id in son_list:
comment_dict[replay_id]["children"].append(row)
print(comment_dict)
print(comment_dict.values())