1

I was using python defaultdict and I noticed this:

from collections import defautdict

class TrieNode(object):
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.is_word = False

temp = TrieNode()

if I do:

temp = temp.children['A'] 

temp will be a new TrieNode instance

but if I do:

   temp = temp.children.get('B')

temp can be None.

Why would d.get(key) vs d[key] behave differently in defaultdict??

Kid_Learning_C
  • 2,605
  • 4
  • 39
  • 71
  • 1
    Because that's what `get` is supposed to do, get a value, if it isn't in the dict, return a default (which defaults to `None`). For a defaultdict, the only thing that changes is that if `__getitem__` recieves a key that isn't in the dict, it *returns a default value from the default factory after setting it for that missing key*. IOW, `.get` and `__getitem__` work differently in regular `dict` objects, so why shouldn't they work differently in `defaultdict` objects? – juanpa.arrivillaga Apr 11 '19 at 22:23
  • 1
    I don't think that's a suitable duplicate. It's about the purpose of the `get` method with regular dictionaries. The question here is: What is the point of a `defaultdict` having a `get` method, when *seemingly* `defaultdict[key]` does the same thing as `dict.get(key)`. – mkrieger1 Apr 11 '19 at 22:45
  • 1
    I'm also not sure that's an appropriate duplicate. I think the OP understands the behaviour of `get` vs `__getitem__` for a regular dictionary. The question was why a `defaultdict`'s `get` method doesn't also use the default factory to create a new value. And I think the answer to that is 'because sometimes you don't want to create a new entry'. – Andrew Guy Apr 11 '19 at 23:25

0 Answers0