4 ms·
You can expand this a bit to make it n-level depth (until you blow the stack). def tree(): return defaultdict(tree) >>> t = tree() >>> t['a']['b']['
by rekwah 5y ago
You can expand this a bit to make it n-level depth (until you blow the stack).
def tree():
return defaultdict(tree)
>>> t = tree()
>>> t['a']['b']['c'] = 10
>>> t
defaultdict(<function tree at 0x10c40df28>, {'a':
defaultdict(<function tree at 0x10c40df28>, {'b':
defaultdict(<function tree at 0x10c40df28>, {'c': 10})})})
- corruptio 5y agoReminds me of perl's autovivification, where you can even mix and match dicts, arrays, and scalars: $M{hello}[4]{world}[0]++ gives you: { 'hello' => [ undef, undef, undef, undef, { 'world' => [ 1 ] } ] }
- css 5y agoThis is really cool, I used it to implement a (very) basic trie: trie_struct: Callable = lambda: defaultdict(trie_struct) trie = trie_struct() for word in words: ref = trie for char in word: ref = ref[char] It won't work with words that substring other words, but its interesting.
- abcxjeb284 5y agoNice! Very expressive way to do n-levels!