Raymond H. quoted Martin L. thusly: > > 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) Then answered with: > 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 This seems a bit too easy to do "as needed" to warrant a new builtin, but that's why we have proposals, I guess: class DefaultingDict(dict): def __init__(self, default): self.default = default def __getitem__(self, key): return self.get(key, self.default()) >>> d = DefaultingDict(lambda: 0) >>> d.update({'a': 1, 'b': 2, 'c': 3}) >>> d {'a': 1, 'c': 3, 'b': 2} >>> for x in ['a', 'b', 'c', 'd']: ... d[x] += 1 ... >>> d {'a': 2, 'c': 4, 'b': 3, 'd': 1} Robert Brewer MIS Amor Ministries fumanchu at amor.org
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