- 先有一個列表,裝了很多字典,我們希望所有parent_id不爲None的都將其放到對應id的鍵children下,並遞歸執行,實現一個多級字典,但遞歸是比較耗內存的,我們將使用引用類型的特殊方法來實現。
# 原始列表
comment_list = [
{'id': 1, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': None},
{'id': 2, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': None},
{'id': 3, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': None},
{'id': 4, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': 2},
{'id': 5, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': 4},
{'id': 6, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': 3},
{'id': 7, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': None},
{'id': 8, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': 5},
{'id': 9, 'user': '殺殺殺', 'comment': '我丟', 'parent_id': 8},
]
# 最後存放結果的列表
comments = []
# 將列表轉化爲字典,並用id作爲comment_dict的鍵和添加一個children鍵值對
comment_dict = {}
for _ in comment_list:
_.update({'children': []})
comment_dict[_['id']] = _
- 轉化爲字典之後的結果:
print(comment_dict)
"""
{
1: {
'id': 1,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': []
},
2: {
'id': 2,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': []
},
3: {
'id': 3,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': []
},
4: {
'id': 4,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 2,
'children': []
},
5: {
'id': 5,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 4,
'children': []
},
6: {
'id': 6,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 3,
'children': []
},
7: {
'id': 7,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': []
},
8: {
'id': 8,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 5,
'children': []
},
9: {
'id': 9,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 8,
'children': []
}
}
"""
- 接下來修改這個字典中有children值的項,將對應的children加入到鍵值對中,
for v in comment_dict.values():
if not v['parent_id']
# 將parent_id爲None,即這裏只放入所有第一級元素
comments.append(v)
else:
"""注意在這裏只修改了原來字典中的children值"""
comment_dict[v['parent_id']]['children'].append(v)
print(comments)
當我們打印comments時會發現已經實現了多級字典
[{
'id': 1,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': []
}, {
'id': 2,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': [{
'id': 4,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 2,
'children': [{
'id': 5,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 4,
'children': [{
'id': 8,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 5,
'children': [{
'id': 9,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 8,
'children': []
}]
}]
}]
}]
}, {
'id': 3,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': [{
'id': 6,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': 3,
'children': []
}]
}, {
'id': 7,
'user': '殺殺殺',
'comment': '我丟',
'parent_id': None,
'children': []
}]