Search code examples
pythonlistdictionarydefaultdictautovivification

Python One-Line Tree using defaultdict. How to reduce the number of arguments required?


I'm using this gist's defaultdict one-line tree.

def tree(): return defaultdict(tree)

Currently, you must provide a separate [] for every node you want to add.

ie:

users = tree()
users['harold']['username']['hrldcpr']
users['handler']['username']['matthandlersux']

My question is, how would I be able to flatten the input so that I could provide a list to achieve the same result?

ie:

users = tree()
users['harold', 'username', 'hrldcpr']
users['handler', 'username', 'matthandlersux']

Thanks for any help!


Solution

  • You can simply define a funcion, say insert to create the node by providing a list and tree as argument.

    def insert(tree, List):
        for node in List:
            tree = tree[node]
    
    users = tree()
    insert(users, ['harold', 'username', 'hrldcpr'])
    

    would create a structure as {'harold' : {'username' : {'hrldcp' : {} } } }