Re:What's New in Python 3.11?
by Latty on Monday June 27, 2022 @02:12AM
(#31891142)
Dictionary merge is a weird one to single out to me, it's an existing operator (|) and functions the same way as a set union over the keys (which uses that operator) in concept, it's a very natural thing that doesn't feel like an expansion of the language, just behaviour you'd expect from the datatype.
[ Parent
| on HN ]
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.
At 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.
Re:What's New in Python 3.11?
by robertlagrant on Monday June 27, 2022 @11:48AM
(#31896239)
Agree. More complex stuff where precedence is tricky can be done in a dictionary comprehension.
That 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}
Re:What's New in Python 3.11?
by wodenokoto on Tuesday June 28, 2022 @08:13AM
(#31906685)
But 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.bool as int is sometimes useful and often infuriating