[Martin] > I do believe that bag classes > got into libraries only for academic reasons such as symmetry. In > particular, they got into Smalltalk because of that reason, and > everybody copies it because Smalltalk has it. This has to stop :-) Some much for "everybody else has one" justification ;-) > Both applications could be implemented if dictionaries had > the notion of a default value, which would be generated > by a callable (whether with or without argument is debatable) > > # count things > d = {} > d.defaultmaker = lambda k:0 > for t in things: > d[t] += 1 > > # sort things by category > d = {} > d.defaultmaker = lambda k:[] > for t in things: > d[category(t)].append(t) These both read cleanly. I really like this idea as a general purpose solution with broad applicability. It fully encapsulates the ideas behind bag construction and building dicts of lists. Instead of a method, it may be better to use a keyword argument in the constructor: d = dict(default = lambda k:[]) for t in things: d[category(t)].append(t) If lambda is made parameterless, it allows type constructors to be used for the most common cases: dict(default=list) # this is clear enough dict(default=int) # this may be too cute Or, lambda could be avoided altogether by cloning a default value dict(default=[]) # individual default values computed by copy([]) dict(default=0) > Having a key in the lambda is probably better, as it would > also allow lazily-filled dictionaries. Can you give an example? Raymond Hettinger
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4