3

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?

albert
  • 8,027
  • 10
  • 48
  • 84
  • 1
    I'm not aware of any other way to get variables names as strings without using `locals()` or something analogous. What would be "comparable" for you, concretely speaking? – BrokenBenchmark Apr 29 '22 at 21:29
  • Depends on what you mean by "comparable". Does passing keyword args like `dict(a=a, b=b, c=c)` sound comparable? (IMO no because it's as repetitive as your current approach anyway) – Pranav Hosangadi Apr 29 '22 at 21:39
  • 1
    Why do you need `a`, `b`, etc as local variables in the first place when you're already declaring them in the dictionary? If you did want to make a dict that copies all the variables in the local scope you could just do `d = locals().copy()`, but even if you're not duplicating the code you're still duplicating the state for no particularly good reason. – Samwise Apr 30 '22 at 00:18

2 Answers2

1

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

fpgx
  • 13
  • 3
-1

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,
)
JL Peyret
  • 10,917
  • 2
  • 54
  • 73