3 ms·
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 oper
by Latty 4y ago
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.
- Someone 4y agoA 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.
- jenny91 4y agoHonestly the set operators too are just screwed: I end up using `set` surprisingly much yet I'm always going back to the docs to figure out what the "or" symbol was, etc.