[Python-ideas] Adding "+" and "+=" operators to dict

Steven D'Aprano steve at pearwood.info
Sat Feb 14 18:46:28 CET 2015


On Sat, Feb 14, 2015 at 07:59:58AM -0800, Chris Barker - NOAA Federal wrote:
> > dict.update() goes back to Python 1.5 and perhaps older.
> 
> Indeed - and not only that, but update() has proved useful, and there
> are no methods  for the other options proposed. Nor have they been
> proposed to be added, AFAIK.
> 
> There is Counter, but as Steven points out -- it's a subclass, partly
> because that behavior isn't usable in the general case of dicts with
> arbitrary keys.
> 
> However, this thread started with a desire for the + and += operators
> -- essentially syntactic sugar ( which I happen to like ). So is there
> a real desire / use case for easy to spell merge-into-new-dict
> behavior at all?

I think there is, for the same reason that there is a use-case for 
sorted() and reversed(). (Only weaker, otherwise we'd already have it.) 
Sometimes you want to update in place, and sometimes you want to make a 
copy and update. So there's definitely a use-case.

(Aside: In Ruby, there's a much stronger tradition of having two methods 
for operations, an in-place one and one which returns a new result.)

But is it a strong use-case? I personally don't think so. I suspect that 
it's more useful in theory than in practice. But other disagree.

I think that "not every three line function needs to be built-in" 
applies to this, but we have sorted() and that's turned out to be 
useful, so perhaps so long as there is *some* uses for this, and there's 
no *harm* in providing it (and somebody provides the patch) the response 
is "sure, it doesn't *need* to be a built-in, but there's not real 
downside to making it such".

(Damning it with faint praise, I know. But maybe somebody will 
demonstrate that there actually are strong uses for this.)

I've already explained that of all the options, extending the dict 
constructor (and update method) to allow multiple arguments seems like 
the best interface to me. As a second-best, a method or function would 
be okay too.

I don't think this is a good match for an operator, and I especially 
dislike the suggestion to use plus. If it had to be an operator, I 
dislike | less strongly than +.

Why |? Because dict keys are sets. (Before Python had sets, we used 
dicts with all the values set to None as a set-like data structure.) 
Updating a dict is conceptually closer to set intersection than 
concatenation:

py> a = {1:None, 2:None}
py> b = {3:None, 2:None}
py> a.update(b)
py> a
{1: None, 2: None, 3: None}
py> {1, 2} | {3, 2}
{1, 2, 3}

But:

py> [1, 2] + [3, 2]
[1, 2, 3, 2]


I'm still not *really* happy about using an operator for this -- it 
doesn't feel like "operator territory" to me -- but if it had to be an 
operator, | is the right one.


-- 
Steve


More information about the Python-ideas mailing list