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()
i in nodesinstead - O(1) instead of O(n) withkeys().