0

In python implementation of trie with defaultdict, it is suspicious how this works?

from collections import defaultdict

def trie():
    return defaultdict(trie)

Creating Trie:

node = trie()

node
# defaultdict(<function __main__.trie()>, {})

node[0]
# defaultdict(<function __main__.trie()>, {})

node == node[0]
# False

node
# defaultdict(<function __main__.trie()>,
#            {0: defaultdict(<function __main__.trie()>, {})})

Can anyone explain how did key=0 got added into trie node?

  • Complete `trie` implementation can be found here: https://stackoverflow.com/a/49357789/11539544 – B.P.Puneeth Pai Mar 08 '21 at 17:59
  • 1
    "how did key=0" ... have you read the documentation for `defaultdict`?? If you try to access a key that doesn't exist, it runs the factory function and assigns it to that key, so when you did `node[0]` – juanpa.arrivillaga Mar 08 '21 at 18:07
  • Thanks @juanpa.arrivillaga. Apologies for silly question. I was confused if self referencing function as `default_factory` had anything to do with it. But it was standard behavior of `defaultdict`. Now I truly understood the implementation of `trie` as `defaultdict` with `default_factory` as self referencing function, instead of simple dict. This is because of **lazy** evaluation. – B.P.Puneeth Pai Mar 09 '21 at 04:13

0 Answers0