4 ms·
That would make the local variable foo in myfunc equal to "bar", as opposed to setting a key named foo in the dictionary kwargs equal to "bar". edit Nevermind
by MPSimmons 5y ago
That would make the local variable foo in myfunc equal to "bar", as opposed to setting a key named foo in the dictionary kwargs equal to "bar".
edit
Nevermind, I see what you mean. Yes, it would be equivalent, but it can be used in other scenarios. This was just the one I thought of.
- alduin32 5y agoA good example scenario for setdefault/defaultdict is grouping a list of tuples : grouped = {} for (key, value) in ungrouped: group = new.setdefault(key, []) group.append(value) defaultdict(list) would make it even shorter, but setdefault() is more general, as it makes it possible to have a "default" value that depends on the key itself. defaultdict combined with late-binding closures also allows to define nested dictionaries : nested_dict = lambda: defaultdict(nested) nested = nested_dict() nested[0][1][2] = "value"