我有字典需要把它填入树中,怎么样?

时间:2017-06-24 09:48:01

标签: python recursion tree

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

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

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

2 个答案:

答案 0 :(得分:0)

你想要这样的东西:

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,父ID,密钥)V(ID,值)。

答案 1 :(得分:0)

  

/!\警告不保证词典中的顺序请参见here

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

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

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

这是另一个命令。

要保持相同的顺序,请在文件file.json和用户中复制/过去此类型 OrderedDict。

<强> 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'}]