Hello Python community,
Following the introduction of dictionary merging and updating operations (|
and |=
) in PEP 584, I am proposing the addition of symmetric difference operations for dictionaries. This would introduce two new operators, ^
for symmetric difference and ^=
for in-place symmetric difference update.
Rationale:
The symmetric difference between two sets is the set of elements that are in either of the sets but not in their intersection. For dictionaries, this operation could similarly be defined as the operation that results in a dictionary containing all key-value pairs from two dictionaries for keys that are exactly in one of the dictionaries. This operation is particularly straightforward and less controversial because it inherently resolves which values to take: if a key exists in both dictionaries, it simply does not appear in the result. This is a natural extension of the dictionary operations introduced in PEP 584 and aligns with Python’s philosophy of consistency and readability.
Proposed Operations and Discussion Points:
Here’s a brief overview of the proposed operations:
d1 ^ d2
: Returns a new dictionary that contains the symmetric difference ofd1
andd2
. If a key exists in both dictionaries, the key-value pair from neither dictionary would be included in the result.d1 ^= d2
: Updatesd1
with the symmetric difference ofd1
andd2
. This is the in-place equivalent of the^
operation.
Additionally, to maintain consistency with Python’s data model, we might consider adding corresponding methods:
dict.symmetric_difference(other)
dict.symmetric_difference_update(other)
Unlike PEP 584, where dict.update
already existed, the decision to add these methods provides a new point of discussion: Should we introduce these methods for symmetry with the set API and for use cases that prefer method calls over operator usage?
I am looking forward to your thoughts and any feedback on this proposal, especially regarding the potential inclusion of these additional methods.
Is it possible to get a PEP started for this?
Thank you!