Python: can we get the value from the dict or object like the ts?

Viewed 98

Isn't the python can get the object or dict like ts:

let test = {a: 1, b: 2, c:3}
const {a, b} = test
The a and b are the key and the variable, it looks simple and not need two line code or for...in to get the a and b.

3 Answers

The closest you'll get is something along the lines of:

a, b = test['a'], test['b']  # dicts
a, b = test.a, test.b        # objects

Or, less repetitive if you have more:

a, b, c = (test[i] for i in ('a', 'b', 'c'))           # dicts
a, b, c = (getattr(test, i) for i in ('a', 'b', 'c'))  # objects

You could probably do funky things with using the locals() or globals() dicts and .updateing them with a set intersection for example, but you should always explicitly declare variables and not muck around with scope dicts.

You can do something like this.

>>>
>>> d = {"a": 1, "b": 2, "c": 3}
>>>
>>> a, b, c = (lambda a, b, c: (a, b, c))(**d)
>>> a
1
>>> b
2
>>> c
3
>>>

Here is another example where we will only get few values.

>>> d2 = {"a": 1, "b": 2, "c": 3, "d": 4}
>>> a, b = (lambda a, b, **kwargs: (a, b))(**d2)
>>> a
1
>>> b
2
>>>

Just use two lines. Anything else which works in one line is too clever, too hard to understand, and too easy to break in the future:

test = {'a': 1, 'b': 2, 'c':3}
a = test['a']
b = test['b']
Related