Skip to content
Advertisement

Python – Tree without classes

How can I implement a tree without using classes in python? I can only use lists, dictionaries and queue. Obviously without the library bintree.

Advertisement

Answer

I usually use defaultdict:

from collections import defaultdict

def Tree():
    return defaultdict(Tree)

Usage:

>>> records = Tree()
>>> records['Artist']['Maria Callas']['Song']['O Mio Babbino Caro']['Year'] = 1965

bonus: Maria Callas singing O Mio Babbino Caro

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement