On Mon, 10 Dec 2007 23:51:00 -0800, kettle wrote: > On Dec 10, 6:58 pm, Peter Otten <[EMAIL PROTECTED]> wrote: >> Well, there's also dict.setdefault() >> >> >>> pairs = ["ab", "ab", "ac", "bc"] >> >>> outer = {} >> >>> for a, b in pairs: >> >> ... inner = outer.setdefault(a, {}) >> ... inner[b] = inner.get(b, 0) + 1 >> ...>>> outer >> >> {'a': {'c': 1, 'b': 2}, 'b': {'c': 1}} >> >> and it's not hard to write your own defaultdict >> >> >>> class Dict(dict): >> >> ... def __getitem__(self, key): >> ... return self.get(key, 0) >> ...>>> d = Dict() >> >>> for c in "abbbcdeafgh": d[c] += 1 >> ... >> >>> d >> >> {'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1} >> >> Peter > > One last question. I've heard the 'Explicit vs. Implicit' argument > but this seems to boil down to a question of general usage case > scenarios and what most people 'expect' for default behavior. The > above defaultdict implementation defining the __getitem__ method seems > like it is more generally useful than the real default. What is the > reasoning behind NOT using this as the default implementation for a > dict in python?
How's that more useful in the general case? Maybe if you come from a language where some default value pops up if the key is not present you are used to write code in a way that exploits this fact. But in the general case!? I need `defaultdict` not very often but want to know if a key is not present in a dictionary. Because most of the time that's a special condition or error that has to be handled or signaled up the call chain. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list