One-line Tree In Python
gist.github.com
One-line Tree In Python
1–10 of 38 posts
Re: One-line Tree In Python
#2Re: One-line Tree In Python
#3I've wanted something like that in Python at different times... thanks!
edit: Ha! The Wiki article even has basically the same code:
def hash(): return defaultdict(hash)
Re: One-line Tree In Python
#4 users = tree()
users.harold.username = 'hrldcpr'
users.handler.username = 'matthandlersux'Re: One-line Tree In Python
#5 defaultdict(lambda: defaultdict(int))
That allows me to organically build dictionaries (mainly for stat building) using operands like +=.Re: One-line Tree In Python
#6I would be interest to see this using the __getattr__ rather than __getitem__, so that this is also possible: users = tree() users.harold.username = 'hrldcpr' users.handler.username = 'matthandlersux'
(Note though that there is/was a small bug(?) in CPython: http://bugs.python.org/issue14658)
Re: One-line Tree In Python
#7I would be interest to see this using the __getattr__ rather than __getitem__, so that this is also possible: users = tree() users.harold.username = 'hrldcpr' users.handler.username = 'matthandlersux'
class attrdict(defaultdict):
def __getattr__(self, key): return self[key]
def __setattr__(self, key, val): self[key]=val
def tree(): return attrdict(tree)
attrdict is indeed a useful thing to have around. I usually base it off on the built in "dict", but as this example shows, it is useful on top of "defaultdict" as well.Re: One-line Tree In Python
#8In Perl, this is called autovivification: https://en.wikipedia.org/wiki/Autovivification I've wanted something like that in Python at different times... thanks! edit: Ha! The Wiki article even has basically the same code: def hash(): return defaultdict(hash)
i wonder whether it will be made part of more languages as JSON-esque nested objects proliferate in our code and minds.
Re: One-line Tree In Python
#9 def tree; Hash.new {|h, k| h[k] = tree }; end
t = tree
t[:foo][:bar] = "foobar" # => {:foo=>{:bar=>"foobar"}}
Probably more idiomatic to do it as a class, though. class Tree
Btw. How do you post nicely formatted code?edit - Thanks!
Re: One-line Tree In Python
#10 dicts_all_the_way_down = lambda:defaultdict(dicts_all_the_way_down)