Dict.union() method

I didn’t see this addressed in PEP 584, so I’d like to ask if it would make sense to have a dict.union() method to match the new | dict union operator. So instead of a | b you could write a.union(b).

This would mirror set.union() and offer people an explicit name which some may find more readable than the | operator.

PEP 584 does have a section called What About The Full set API?, but that seems focused on supporting all the set operators.

Perhaps this suggestion to offer named methods that mirror the new dict operators should just be added to that section of the PEP and addressed if/when the proposed follow-on PEP materializes.

| between sets is a union operator, but | between dicts is a “merge” operator. It’s not the same as a union since dict values may not be unique. If you wanted an explicit method, it would likely be named dict.merge().

The other new operator added to dict (|=) is equivalent to the existing dict.update(), so no additions required there.

It’s also not clear what benefits dict.merge() (or whatever this is named) would provide. set.union() is a useful addition to | (i.e. set.__or__()) since it accepts an arbitrary iterable, but it’s not as obvious what type dict.merge() would accept. The function would be arguably redundant if it only takes a dict or subclass.

Thanks for the clarification, @pylang. That’s correct, it’s a merge since key collisions result in one value taking precedence over another.

so additions required there.

You meant no additions required there, right?

@uranusjr - I’d say having an explicitly named method is generally a benefit for those of us who find them more readable than symbols. But you’re right, there should perhaps be a stronger case made for an explicit dict.merge() method.

How about if dict.merge() worked similarly to set.union() in that you can provide an iterable of dicts, where the last dict wins any key collisions?

To follow the format of the set.union() docs:

dict.merge(*others) == dict | other | ...

Yes correct. “no additions required” (edited)

Yeah the dict.keys() are actually set-like. You can use set operations directly on them. It’s pretty cool.