1

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!

JmsBtlr111
  • 31
  • 1
  • 5
  • Given that tree is a dict, may try this: http://stackoverflow.com/questions/15077973/how-can-i-access-a-deeply-nested-dictionary-using-tuples – fredtantini Sep 29 '14 at 11:08
  • That is definitely the functionality I want, I will have a look into this one. Thanks! – JmsBtlr111 Sep 29 '14 at 11:13
  • You could create a class and implement your own `__getitem__` and `__setitem__`, but that is beyond the scope of a sensible SO question. – jonrsharpe Sep 29 '14 at 11:14
  • Yeah, the example that @fredtantini linked to does provide an example for that method. Thanks! – JmsBtlr111 Sep 29 '14 at 11:21

1 Answers1

3

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' : {} } } }

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52