3 ms·
Because it's actually (somewhat confusingly, called setdefault). >>> a = {1:'foo',2:'blah'} >>> a.setdefault(1,'default') 'foo' >>> a.setdefaul
by TylerE 15y ago
Because 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.