【问题标题】:I have dictionary need to fill it into tree, how to?我有字典需要将它填充到树中,如何?
【发布时间】:2017-06-24 09:48:01
【问题描述】:

我有这样的字典,需要将它填充到数组或数据库中的树状方案中,例如:

a = {"seasons": "episodes", "peka": {"lol": "wow", "kek": {"wtf": "is this"}}, "ololo": "wololo"} 

"seasons"拥有自己的ID = 1Parent_ID = NONE 和值 "episode" 有自己的 ID = 2Parent_ID = 1 , 和其他字典一样。

【问题讨论】:

    标签: python recursion tree


    【解决方案1】:

    /!\ WARNING 不保证字典中的顺序见here

    a = { 
          "seasons": "episodes", 
          "peka": {"lol": "wow", "kek": {"wtf": "is this"}}, 
          "ololo": "wololo"
        }
    

    对象a是字典,不保证(key, value)的顺序,也就是说随机如果你做print(a),你有:

    {'ololo': 'wololo', 'peka': {'kek': {'wtf': 'is this'}, 'lol': 'wow'}, 'seasons': 'episodes'}
    

    这是另一个命令。

    要保持相同的顺序,请在文件file.json 和用户中复制/粘贴此类型 有序字典。

    file.json

    { 
      "seasons": "episodes", 
      "peka": {"lol": "wow", "kek": {"wtf": "is this"}}, 
      "ololo": "wololo"
    }
    

    这里是你的解决方案:

    import json
    from collections import OrderedDict
    from pprint import pprint
    
    with open('file.json', 'r') as filename:
        a = json.load(filename, object_pairs_hook=OrderedDict)
    
    
    def build_item(_id, parent_id, value):
        return {'ID': _id, 'Parent_ID': parent_id, 'Value': value}
    
    
    def dfs(_id, root, tree):
        _id += 1
        flat_tree = [build_item(_id, None, root)]
        stack = [(_id, tree)]
        while len(stack) != 0:
            parent_id, tree = stack.pop(0)
            if isinstance(tree, dict):
                for value in tree.keys():
                    _id += 1
                    flat_tree.append(build_item(_id, parent_id, value))
                    stack.append((_id, tree[value]))
            else:
                value = tree
                _id += 1
                flat_tree.append(build_item(_id, parent_id, value))
        return _id, flat_tree
    
    
    def convert_dict_to_flat_tree(d):
        flat_trees = list()
        _id = 0
        for root, tree in d.items():
            _id, flat_tree = dfs(_id, root, tree)
            flat_trees.extend(flat_tree)
        return flat_trees
    
    
    flat_tree = convert_dict_to_flat_tree(a)
    
    pprint(flat_tree)
    

    输出:

    [{'ID': 1, 'Parent_ID': None, 'Value': 'seasons'},
     {'ID': 2, 'Parent_ID': 1, 'Value': 'episodes'},
     {'ID': 3, 'Parent_ID': None, 'Value': 'peka'},
     {'ID': 4, 'Parent_ID': 3, 'Value': 'lol'},
     {'ID': 5, 'Parent_ID': 3, 'Value': 'kek'},
     {'ID': 6, 'Parent_ID': 4, 'Value': 'wow'},
     {'ID': 7, 'Parent_ID': 5, 'Value': 'wtf'},
     {'ID': 8, 'Parent_ID': 7, 'Value': 'is this'},
     {'ID': 9, 'Parent_ID': None, 'Value': 'ololo'},
     {'ID': 10, 'Parent_ID': 9, 'Value': 'wololo'}]
    

    【讨论】:

    • 我得到这个输出:{'ID': 1, 'Parent_ID': None, 'Value': 'seasons'} {'ID': 2, 'Parent_ID': 1, 'Value ':'episodes'} {'ID':3,'Parent_ID':无,'Value':'peka'} {'ID':4,'Parent_ID':3,'Value':'lol'} {' ID':5,'Parent_ID':3,'Value':'kek'} {'ID':6,'Parent_ID':5,'Value':'wtf'} {'ID':7,'Parent_ID' :6,'值':'这是'} {'ID':8,'Parent_ID':7,'值':'哇'} {'ID':9,'Parent_ID':无,'值': 'ololo'} {'ID': 10, 'Parent_ID': 9, '值': 'wololo'}
    • 我将输出更改为使用pprint 获得不错的输出。结果正确吗?
    • 在你的输出值 = "wow" 有正确的 id 和 parent_id (6 ,5) ,我有 "wow" 作为 id =8 和 parent_id = 7
    • 正常情况下字典中的顺序不保证见stackoverflow.com/questions/23965870/…
    • @RonBurgundy 你可以吗?
    【解决方案2】:

    你想要这样的东西:

    a = {"seasons": "episodes", "peka": {"lol": "wow", "kek": {"wtf": "is this"}}, "ololo": "wololo"}
    
    _id = {}
    
    def newid():
        id = _id.setdefault('foo', 0)
        _id['foo'] += 1
        return id
    
    def flat(dic, parent):
        for k,v in dic.items():
            id = newid()
            yield (id, parent, k, v if not isinstance(v, dict) else None)
            if isinstance(v, dict):
               for tup in flat(v, id):
                   yield tup
    
    print list(flat(a, newid()))
    

    哪些打印:

    [(1, 0, 'seasons', 'episodes'), 
     (2, 0, 'ololo', 'wololo'), 
     (3, 0, 'peka', None), 
     (4, 3, 'kek', None), 
     (5, 4, 'wtf', 'is this'), 
     (6, 3, 'lol', 'wow')]
    

    这些是(ID、Parent ID、Key、Value?)形式的元组。我宁愿输出 E(ID, Parent ID, Key) V(ID, Value)。

    【讨论】:

    • 我需要打印出每个项目(k,v)并带有 ID 和 Parent_ID
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多