albert
albert

Reputation: 8623

ES6-like object shorthand for Python dictionary

For API interaction, I need to 'summarize' some variables in a dictionary. A basic approach would be like

a = 1
b = 2
c = 3

d = {
    'a': a,
    'b': b,
    'c': c,
}

which seems to be somehow repetitive, especially for 15+ variables.

To reduce optical clutter and repetition, I wondered whether Python does have something like ES6's object shorthand which allows to do:

const a = 1;
const b = 2;
const c = 3;

const obj = {
    a,
    b,
    c
}

I found an answer to a similar question, but accessing the variables via the locals() function seems to be a somehow ugly workaround.

Does Python support an ES6-comparable shorthand notation to create a dictionary from variables?

Upvotes: 4

Views: 705

Answers (2)

JL Peyret
JL Peyret

Reputation: 12204

This ought to lessen typing. The key is to the dict constructor rather than the literal declaration syntax {}

#can also use outside vars
d = 4

obj = dict(
a = 1,
b = 2,
c = 3,
d = d,
)

Upvotes: -2

fpgx
fpgx

Reputation: 23

What you're looking for doesn't exist in Python.

Upvotes: 2

Related Questions