4 ms·
This may have been mentioned elsewhere, but Python already has a syntactic way of merging dictionaries: d = {**d1, **d2} which arguably has all the visual b
by thomasahle 7y ago
This may have been mentioned elsewhere, but Python already has a syntactic way of merging dictionaries:
d = {**d1, **d2}
which arguably has all the visual benefits argued for.
- rat9988 7y agod = d1 + d2 is way easier to parse.
- tremon 7y agoAs mentioned elsewhere in this thread, the mathematical + operator is commutative: d1 + d2 == d2 + d1. How does the + operator maintain that commutativity in the face of duplicate keys?
- rat9988 7y agoThe + symbol doesn't denote any particural operation mathematics. it widely used for vector space where commutativity is a condition though. A symbol's property depend on the operation, the multiplication symbol for example is commutative in some cases and not in others.
- aratakareigen 7y agoIt is a convention, not a rule, in mathematics to use (+) to represent operations that are commutative (i.e. abelian) groups. But this convention is not at all respected in programming (e.g. + for string concatenation in many languages) so I have to admit that it's pretty irrelevant.
- NoodleIncident 7y agoThe war to keep programming operators at all consistent with mathematics was lost long ago, with `=` and `==` being the worst offenders.
- nemetroid 7y agoTo be fair, mathematics uses = to indicate assignment as well, e.g. for summation limits.
- krenel 7y agoOperators are polymorphic. While the + operator is commutative when using on integers/float, it is not currently when used on lists: >>> [1,2,3] + [4,5,6] [1, 2, 3, 4, 5, 6] >>> [4,5,6] + [1,2,3] [4, 5, 6, 1, 2, 3] In dictionaries it would behave differently as well (duplicated keys, etc.)
- shawnz 7y agoIt's also not commutative on strings and that is the case in many languages, not just Python.
- Hwatwasthat 7y agoThat already falls apart when the + operator is used for string concatenation so I think the answer is people are using it in a less rigorous sense already.
- efdee 7y agoThe + here is not a mathematical + per se.
- bobbiechen 7y agoThe PEP [1] addresses this: Few people would be able to guess what it means the first time they see it, or think of it as the "obvious way" to merge two dicts [...] {d1, d2} ignores the types of the mappings and always returns a dict. type(d1)({d1, d2}) fails for dict subclasses such as defaultdict that have an incompatible __init__ method. Though I'm not personally convinced that + would be more obvious or that dict subtypes are merged often enough for this to matter. [1] https://www.python.org/dev/peps/pep-0584/#d1-d2 https://www.python.org/dev/peps/pep-0584/#d1-d2
- thomasahle 7y agoGreat PEP :-) It also mentions further down, that for lists er have both a + b and [*a, *b] As well as other ones I hadn't even thought about like a[len(a):] = b.