4 ms·
Unlike some of the other commenters, I'm fine with the + specification. + hasn't been commutative in Python for a long time. But the - bothers me, and nobody e
by jerf 8y ago
Unlike some of the other commenters, I'm fine with the + specification. + hasn't been commutative in Python for a long time.
But the - bothers me, and nobody else seems to have mentioned this. {"a": 1} - {"a": 1} = {}, sure, but it is way less obvious to me that {"a": 1} - {"a": 2} = {}, and not {"a": 1}. If you consider dictionaries as an unordered list of tuples (key, value) where keys happen to be unique and as a result of that you get nice O()-factors on access, that doesn't make sense. You went to remove ("a", 2), but saw ("a", 1) and thought, "eh, close enough". But it's not the same thing.
If you think of a dict as a set that happens to have associated values, the specification makes more sense, but if you dig into that line of thought, that turns out to be a rather weird way of thinking of them. Values really shouldn't be thought of as second-class citizens of a dict. If you are going to go this route though, {"a": 1} - {"a"} = {} (where the right-hand side is a set) actually makes more sense, without the spurious value on the right-hand side.
I'd actually rather conceive of the - operation as a "dict minus an iterable that will yield keys to remove". This has the advantage of recovering the original {"a": 1} - {"a": 2} = {} semantics that probably is what people want in practice, just via a different method. But locking the right-hand side to a dict makes it weird.
- marcosdumay 8y ago> Values really shouldn't be thought of as second-class citizens of a dict. Aren't they? If I do `d["a"] = 1; d["a"] = 2` the first assignment is completely gone after the second, I don't get a set with superimposed values on the "a" key.
- Areading314 8y agoIts consistent with iteration over a dict: for k in my_dict: print(my_dict[k]) In this example it is implied that unless you specify .items(), you are only considering keys in the iteration. This would apply to the + and - operations too as I understand
- ken 8y agoUsing - to mean "here's a dict and a seq -- remove all the seq's keys from the dict" would be useful and consistent, but they specifically prohibit that. They require the rhs to be a dict, too, even though the values are never used. Why?
- Areading314 8y agoGood point, although you'd need to make sure your seq only has unique values. Other than that I don't see why you should have to write {k: v for k, v in d.items() if k not in seq}