3 ms·
> While not as powerful as destructuring in other languages (I still wish we could unpack dicts as JS does with objects) Like this? In [1]: a = {1: 10, 2:
by pedrovhb 3y ago
> While not as powerful as destructuring in other languages (I still wish we could unpack dicts as JS does with objects)
Like this?
In [1]: a = {1: 10, 2: 20}
In [2]: b = {3: 30, **a}
In [4]: b
Out[4]: {3: 30, 1: 10, 2: 20}
Or pattern matching?
In [6]: match b:
...: case {3: somethingelse, 1: foo}:
...: print(somethingelse, foo)
30 10
- babel_ 3y agoI think they mean {a: x, b: y, *c} = d, which is a nice idea now we have a stable order to dicts, but I've rarely come across times when I needed this that I can't simply use .items() and such for, or care about more general pattern matching like values for specific keys, which you can just do a, b = d["a"], d["b"] with little loss of clarity, sure {"a": a, "b": b} = d is cute and all, and maybe we'll oneday see it now we have match as syntactic precedent, but I don't really feel concerned by its absence.
- tuukkah 3y agoThey mean you can unpack lists: a, b, *rest = args So why not dicts: "a": a, "b": b, **rest = kw_args Also, in JS the destructuring does not fail because of extra elements even if you don't capture them. Further, in JS you don't need the quotes, and a: a can be shortened as simply a. You'll need the dict curly braces though. Thus the same in JS, which you see a lot e.g. for properties of a component in React code: { a, b } = props; It's quite nice with no excessive "line noise" and even makes up for JS functions lacking real keyword arguments.
- BiteCode_dev 3y agoAlso JS allows you to define default values if the key is missing, and Python's pattern matching doesn't.