Reputation: 8623
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
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