How can I organize a dictionary?

I find it difficult to complicate the dictionary as follows: the given input number 5, then the search key=5in the dictionary placed it first, and then its first value 4and find key=4in the dictionary and put its value as the second, and then the second value 5, which 3, and find key=3in the dictionary and place it value as third

Values ​​will consist of one or two integers

I am working on drawing a binary tree, so it will be easier if the root node (parent), which is 5 here, is first, and then its children, children, etc. next

I tried to organize it using OrderedDict, but I could not find it

Can someone help me?

Input:

{8: [9], 3: [6, 8], 4: [2, 1], 5: [4, 3], 6: [0, 7]}

Output:

{5: [4, 3], 4: [2, 1], 3: [6, 8], 6: [0, 7], 8: [9]} 

Updated code:

def dfs(cur, prev, edges, res):
    for next in edges[cur]:
        if next == prev: continue

        res.setdefault(cur, []).append(next)

        dfs(next, cur, edges, res)


def construct_tree(edges, root):
    d = {}
    x = []
    for edge in edges:
        u, v = edge
        d.setdefault(u, []).append(v)
        d.setdefault(v, []).append(u)

    res = {}

    dfs(root, -1, d, res)

    return res

if __name__ == '__main__':

        root_node = 5
        edges = [[2, 4], [4, 1], [0, 6], [7, 6], [8, 9], [4, 5], [6, 3], [3, 5], [3, 8]]
        print((construct_tree(edges, root_node)))
+4
2

, , . , , , .

/, , , . , OrderedDict , .

from collections import OrderedDict
from queue import Queue

sample_dict = {8: [9], 3: [6, 8], 4: [2, 1], 5: [4, 3], 6: [0, 7]}

node -, , , , , !

def sort_the_dict(in_, firstkey):
    # in_ is your sample data.
    result_dict = OrderedDict()
    q = Queue()
    q.put_nowait(firstkey)

    while not q.empty():
        k = q.get_nowait():
        v = in_.get(k)
        if v is not None:
            # if a value exists for that key
            result_dict[k] = v
            for vv in v:
                q.put_nowait(vv)

    return result_dict
+3
from collections import OrderedDict

d = {8: [9], 3: [6, 8], 4: [2, 1], 5: [4, 3], 6: [0, 7]}

sorted_keys = sorted([x for x in d])
sorted_d = OrderedDict(zip(sorted_keys, [d[k] for k in sorted_keys]))

, , sorted_keys , dict. , , , , , , .

+2

All Articles