3 ms·
No he doesn't. defaultdict provides a default value for ALL missing values. His approach allows him to target one key in particular, and is a very common python
by TylerE 15y ago
No he doesn't. defaultdict provides a default value for ALL missing values. His approach allows him to target one key in particular, and is a very common python idiom.
- gaius 15y agoI'm confused - where does that come from? >>> x.getDefault(1, 'Que?') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> x.getDefault(1, 'Que?') AttributeError: 'dict' object has no attribute 'getDefault'
- TylerE 15y agoBecause it's actually (somewhat confusingly, called setdefault). >>> a = {1:'foo',2:'blah'} >>> a.setdefault(1,'default') 'foo' >>> a.setdefault(4,'default') 'default' >>> a {1: 'foo', 2: 'blah', 4: 'default'} This actually updates the underlying datastructure. Very handy when you want to deal with nested structures, since you can do something like: matches.setdefault(keyword,[]).append(s) This will append s to the list in matches[keyword] if it exists, or set matches[keyword] to [] and then append.
- phzbOx 15y agoWops, you both are right, thanks for pointing it out. I meant to say dict.get, i.e. {'a':1}.get('b',5)