gpt4 book ai didi

python - 基于深度信息的多级dict字典列表

转载 作者:行者123 更新时间:2023-12-03 16:17:31 24 4
gpt4 key购买 nike

我有一些数据,或多或少是这样的:

[
{"tag": "A", "level":0},
{"tag": "B", "level":1},
{"tag": "D", "level":2},
{"tag": "F", "level":3},
{"tag": "G", "level":4},
{"tag": "E", "level":2},
{"tag": "H", "level":3},
{"tag": "I", "level":3},
{"tag": "C", "level":1},
{"tag": "J", "level":2},
]

我想将其转换为基于深度级别(键“级别”)的多级字典:
{
"A": {"level": 0, "children": {
"B": {"level": 1, "children": {
"D": {"level": 2, "children": {
"F": {"level": 3, "children": {
"G": {"level": 4, "children": {}}}}}},
"E": {"level": 2, "children": {
"H": {"level": 3, "children": {}},
"I": {"level": 3, "children": {}}}}}},
"C": {"level": 1, "children": {
"J": {"level": 2, "children": {}}}}}}
}

我现在所能想到的只是这小段代码...显然在以下几项之后就中断了:
def list2multilevel(list):
children = {}
parent = list.pop(0)
tag = parent.get("Tag")
level = parent.get("Level")
for child in list:
ctag = child.get("Tag")
clevel = child.get("Level")
if clevel == level + 1:
children.update(list2multilevel(list))
elif clevel <= level:
print(clevel, level)
break
return {tag: children}

最初在星期五坐下来,应该只是个小练习……。

最佳答案

data = [
{"tag": "A", "level": 0},
{"tag": "B", "level": 1},
{"tag": "D", "level": 2},
{"tag": "F", "level": 3},
{"tag": "G", "level": 4},
{"tag": "E", "level": 2},
{"tag": "H", "level": 3},
{"tag": "I", "level": 3},
{"tag": "C", "level": 1},
{"tag": "J", "level": 2},
]

root = {'level': -1, 'children': {}}
parents = {-1: root}
for datum in data:
level = datum['level']
parents[level] = parents[level - 1]['children'][datum['tag']] = {
'level': datum['level'],
'children': {},
}
result = root['children']
print(result)

输出:

{'A': {'level': 0, 'children': {'B': {'level': 1, 'children': {'D': {'level': 2, 'children': {'F': {'level': 3, 'children': {'G': {'level': 4, 'children': {}}}}}}, 'E': {'level': 2, 'children': {'H': {'level': 3, 'children': {}}, 'I': {'level': 3, 'children': {}}}}}}, 'C': {'level': 1, 'children': {'J': {'level': 2, 'children': {}}}}}}}

限制:
  • level >= 0
  • 任何level都不能大于之前出现的最大级别的+1

  • 解释:
  • parents是一本字典,用于记住每个级别的最后一个元素。
  • root是一个起点(虚拟元素)。
  • 逻辑:
  • -1级别开始,该级别指示root
  • 制作一个项目并将其注册到 parent 的children中。
  • 将相同项目更新为parents字典。
  • 重复。
  • 提取root['children']
  • 关于python - 基于深度信息的多级dict字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61057046/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com