3 ms·
A problem with dictionary merge that doesn’t exist with sets is what to do with the values if you have a key in both dictionaries. Do you keep the value on the
by Someone 4y ago
A problem with dictionary merge that doesn’t exist with sets is what to do with the values if you have a key in both dictionaries.
Do you keep the value on the left, the value on the right, error out, try merging the values (if so: how?), add a parameter allowing the user to make that choice, require the user to pass a lambda?
I don’t think there’s a ‘best’ answer here, but if you want to make one of them easier to write as a|b, you can only support one.
- duckerude 4y agoThat problem also exists in sets because some values that aren't interchangeable still compare equal: >>> {1} | {1.0} | {True} {1} But the behavior for dicts is surprising even in that light: >>> {1: 1} | {1.0: 1.0} | {True: True} {1: True}
- kzrdude 4y agobool as int is sometimes useful and often infuriating
- wodenokoto 4y agoBut that is not really the `|` operators fault. You get the exact same behaviour when you create a dictionary. >>> {1: 1, 1.0: 1.0, True: True} {1: True} So `|` between dictionaries behaves just as you'd expect, if your expectations about creating a dictionary are correct. I think that's very reasonable.
- Latty 4y agoAt the end of the day people were doing {**a, **b} or dict(d1.items() | d2.items()) (which is subtly different in that set order is arbitrary so which "wins" in the duplicate key case is arbitrary) in the wild, so I think supporting a natural dict-level union is the better option, even if it can't be all things to all people.
- robertlagrant 4y agoAgree. More complex stuff where precedence is tricky can be done in a dictionary comprehension.