Raymond Hettinger wrote: > I would like to get everyone's thoughts on two new dictionary methods: > > def count(self, value, qty=1): > try: > self[key] += qty > except KeyError: > self[key] = qty > > def appendlist(self, key, *values): > try: > self[key].extend(values) > except KeyError: > self[key] = list(values) >
-0.9 Not impressed, they feel too specific for being builtin dictionary methods and give the impression of just trying to save a few lines here and there. I don't feel the names convey the functionality of the methods either. I know there's the speed argument but I'd rather not have these on the dict at all. +0.1 I sort of feel a slight need for this. But where would you stop? What if people decrement lots? what if next there's a need for division? How would you determine how you add the item to the key if it already exists? In a general way: mydict.set(key, value=None, default=None, how=operator.setitem) This feels slightly better as it's not tied down to what sort of item you're setting. But: >>> for word in words: >>> mydict.set(word, 1, 0, operator.add) I dunno, feels a bit verbose maybe. > The setdefault() method would continue to exist but would likely not make it > into Py3.0. I agree that setdefault is wart though. And for dict.default = value: (Quoth RON): """With a preset default mode, it then becomes possible to inadvertently create default values that will cause problems without knowing it. So then we have to remember to change the setdefault value to None or null to avoid problems. Ouch!""" Agreed, -1 there then. > PROBLEMS BEING SOLVED > --------------------- > > The readability issues with the existing constructs are: > > * They are awkward to teach, create, read, and review. > * Their wording tends to hide the real meaning (accumulation). > * The meaning of setdefault() 's method name is not self-evident. I feel this only really applies for setdefault (which I wouldn't be sorry to see the back of). And your examples: d[key] = d.get(key, 0) + qty d.setdefault(key, []).extend(values) Would better be written in a long-handed fashion anyway as per the implementations were suggested: try: d[key] += qty except KeyError: d[key] = 0 Yeah, yeah, I know, speed. But not like this. Sorry. -- http://mail.python.org/mailman/listinfo/python-list