3 ms·
Python's defaultdict also behaves like this, inserting the nonexistent entry into the dict: from collections import defaultdict m = defaultdict(int)
by MatmaRex 4y ago
Python's defaultdict also behaves like this, inserting the nonexistent entry into the dict:
from collections import defaultdict
m = defaultdict(int)
m["nonexistent"]
len(m) # => 1
There are examples of the opposite too, though. Ruby's Hash does not insert the entry:
m = Hash.new(0)
m["nonexistent"]
m.length # => 0
- lifthrasiir 4y agoPython's defaultdict is aptly named to indicate this behavior (the bare `dict` won't do this). `std::map` isn't.
- masklinn 4y ago> There are examples of the opposite too, though. Ruby's Hash does not insert the entry: It does if you initialise the hash with a block to do so: m = Hash.new {|h, k| h[k] = 0} m["nonexistent"] m.length # => 1 That is, essentially, what defaultdict does. Just through subclassing (because `dict` does not provide such a fallback, but it has a magic method you can override to customise the mapping's behaviour in that case).
- kragen 4y agothis famously introduced bugs into norvig's published code (i forget if it was the sudoku solver or the spell checker) that nobody noticed for years if norvig isn't smart enough to use defaultdict without introducing bugs then i'm not either
- abecedarius 4y agoiirc it was the spellchecker. My memory is fuzzy and unreliable but what it's claiming is that the first version on his webpage had that bug, he fixed it, and later I pointed out another bug of the same type. Or something like that! (I am sure I never reported anything about the sudoku solver, since I never studied it.)
- kragen 4y agothanks!