other-languages 2024-01-30

Is there something akin to destructuring maps (dicts) in Python? Like (let [{:keys [foo bar]} {:foo 42 :bar "hello"}] ...)

foo(**a_dict) destrcutures the dict and can pass it to a function with named arguments

nice - any reference you can point at? (not sure what to google 😅)

Splat operator?

python kwargs

if it is about picking data from a Python dict, I usually do something like this, a comprehension:

{k: v for k, v in data.items() if k in {"foo", "bar"}}
(also, could be put in a pick function, accepting a dict and a set of keys)
def pick(data: dict, keys: set) -> dict:
    return {k: v for k, v in data.items() if k in keys}
or, the opposite 😄
def omit(data: dict, keys: set) -> dict:
    return {k: v for k, v in data.items() if k not in keys}

If it's the values only, you can return {v (the return type will be a set )

an example of @ben.sless’s suggestion, without a named function:

>>> (lambda x, y: print("x=", x, "y=", y))(**{"x": 10, "y": 20})
x= 10 y= 20
so it could be used with a lambda instead of a named function — but readability may suffer. You could return a tuple from the function and bind to that,
>>> x, y = (lambda x, y: (x, y))(**{"x": 10, "y": 20})
>>> x, y
(10, 20)
Still skeptical about readability. Yet another attempt:
>>> d = {"x": 10, "y": 20}
>>> splat = lambda s, d: [d[x] for x in s.split()]
>>> x, y = splat("x y", d)
>>> x, y
(10, 20)
still skeptical about readability. You be the judge 🙂

I have a lot to judge Python for, think I'll pass

😅 2