Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a += and + operator for dictionaries #14142

Open
dcbaker opened this issue Jan 15, 2025 · 1 comment
Open

Add a += and + operator for dictionaries #14142

dcbaker opened this issue Jan 15, 2025 · 1 comment
Milestone

Comments

@dcbaker
Copy link
Member

dcbaker commented Jan 15, 2025

Like for arrays, I'd imagine that if you wrote something like:

x = {'foo' : 1}
x += {'bar': 2}

that this would be equivalent to:

x = {'foo' : 1} + {'bar': 2}

The only question that remains is what to do with key collisions. There are two possibilities that seem acceptable to me:

  1. The RHS dict overrides the LHS
    Equivalent python
    d = d1.copy()
    d.update(d2)
    return d
  2. keys existing in both dicts is an error
@bonzini bonzini added this to the 1.8 milestone Jan 19, 2025
@bruchar1
Copy link
Member

Python does not support + and += on dict, but uses | and |= instead (since 3.9), updating values like with your option 1.

That being said, I would definitively not add a new kind of operator just for that. Therefore, I think using + and += is a viable option. Another option would be to use a method instead, like update (but with a verb that makes it clear it returns a copy and do not modify values in-place).

A third solution for collision would be to perform a recursive merge (lhs values are updated from rhs, but if both values are dict themselves, they are merged, and if both values are array, values from rhs are appended to lhs)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants