3

I have a nested dictionary like this that I want to use to populate a hierarchical treeview.

hierarchy = {
                'a': {
                    'b': {
                        'e': 'DATA',
                        'f': 'DATA',
                        'g': {
                            'h': 'DATA',
                            'i': 'DATA',
                            'j': 'DATA'
                        },
                        'm': {
                            'n': 'DATA',
                            'o': 'DATA',
                            'p': 'DATA'
                        }
                    },
                    'c': 'DATA',
                    'd': 'DATA'
                }
            }

The code should walk down the nested dictionary and create appropriate tk treeview nodes. Basically replicating PyCharm's view that lets you open a nested dictionary and drill down as far as you like.

I am pasting the code I wrote below but the recursion doesn't work at all. I am only pasting it for the convenience of not having to re-create a tk window etc.

root = tk.Tk()
root.geometry("900x900")
tree = ttk.Treeview(root)
ttk.Style().configure('Treeview', rowheight=30)
tree["columns"] = ("one", "two", 'three')
tree.column("one", width=100)
tree.column("two", width=100)
tree.heading("one", text="a")
tree.heading("two", text="b")
tree.heading("three", text="c")

nodes = {}

def add_node(elem):
    for i, j in elem.items():
        if isinstance(j, dict):
            add_node(j)
        else:
            if i in nodes.keys():
                nodes[j] = tree.insert(i, 1, j, text=j)
            else:
                nodes[i] = tree.insert("", 1, i, text=i)

for k, v in hierarchy.items():
    add_node(k)

tree.pack(expand=True, fill='both')
root.mainloop()
root.destroy()
2
  • 1
    Unrelated: use i in nodes instead - O(1) instead of O(n) with keys(). Commented Jul 15, 2019 at 9:10
  • That is bizzare, but thank you I did not know that. Commented Jul 15, 2019 at 9:13

1 Answer 1

3

I figured it out:

root = tk.Tk()
root.geometry("900x900")
tree = ttk.Treeview(root)
ttk.Style().configure('Treeview', rowheight=30)
tree["columns"] = ("one", "two", 'three')
tree.column("one", width=100)
tree.column("two", width=100)
tree.heading("one", text="a")
tree.heading("two", text="b")
tree.heading("three", text="c")

def add_node(k, v):
    for i, j in v.items():
        tree.insert(k, 1, i, text=i)
        if isinstance(j, dict):
            add_node(i, j)

for k, v in hierarchy.items():
    tree.insert("", 1, k, text=k)
    add_node(k, v)

tree.pack(expand=True, fill='both')
root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.