[Python-ideas] Dict joining using + and +=

Serhiy Storchaka storchaka at gmail.com
Tue Mar 5 02:23:20 EST 2019


04.03.19 21:24, Guido van Rossum пише:
> * Dicts are not like sets because the ordering operators (<, <=, >, >=) 
> are not defined on dicts, but they implement subset comparisons for 
> sets. I think this is another argument pleading against | as the 
> operator to combine two dicts.

Well, I suppose that the next proposition will be to implement the 
ordering operators for dicts. Because why not? Lists and numbers support 
them. /sarcasm/

Jokes aside, dicts have more common with sets than with sequences. Both 
can not contain duplicated keys/elements. Both have the constant 
computational complexity of the containment test. For both the size of 
the merging/unioning can be less than the sum of sizes of original 
containers. Both have the same restrictions for keys/elements (hashability).

> * Regarding how to construct the new set in __add__, I now think this 
> should be done like this:
> 
> class dict:
>      <other methods>
>      def __add__(self, other):
>          <checks that other makes sense, else return NotImplemented>
>          new = self.copy()  # A subclass may or may not choose to override
>          new.update(other)
>          return new
> 
> AFAICT this will give the expected result for defaultdict -- it keeps 
> the default factory from the left operand (i.e., self).

No one builtin type that implements __add__ uses the copy() method. Dict 
would be the only exception from the general rule.

And it would be much less efficient than {**d1, **d2}.

> * Regarding how often this is needed, we know that this is proposed and 
> discussed at length every few years, so I think this will fill a real need.

And every time this proposition was rejected. What has been changed 
since it was rejected the last time? We now have the expression form of 
dict merging ({**d1, **d2}), this should be decrease the need of the 
plus operator for dicts.



More information about the Python-ideas mailing list