Preferred Python idiom for handling non-existing dictionary keys and why?
Tim Peters
tim.one at comcast.net
Fri Oct 10 15:54:53 EDT 2003
[Skip Montanaro]
> d.setdefault() never made any sense to me (IOW, to use it I always
> had to look it up). The semantics of what it does just never stick
> in my brain.
Mentally change the name to getorset() and I bet it will be easier.
d.getorset(x, default) gets the value of d[x] if there is one already, or
sets d[x] to default and returns that. I think Guido would have changed the
name to something sane, except he was pissed at me that day <wink>.
> Consequently, even though it's less efficient I generally write such
> loops like this:
>
> d = {}
> for (key, val) in some_items:
> lst = d.get(key) or []
> lst.append(val)
> d[key] = lst
If d[key] originally has a false value (0 or [] or {} or None or ...), this
will end up replacing it. It works in the specific context of this "build a
list" loop, but in the general case can screw up.
More information about the Python-list
mailing list