python词典的ES6般的物体速记

发布于 2025-01-25 05:41:14 字数 894 浏览 2 评论 0原文

对于API相互作用,我需要在字典中“总结”一些变量。一种基本的方法似乎

a = 1
b = 2
c = 3

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

是重复的,尤其是对于15个以上的变量。

为了减少光学混乱和重复,我想知道python是否确实有 es6的对象速记

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

const obj = {
    a,
    b,
    c
}

我找到了回答类似问题的答案但是,通过 locals 函数< /a>似乎是一种丑陋的解决方法。

Python是否支持ES6可相比的速记符号来创建变量的字典?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

莳間冲淡了誓言ζ 2025-02-01 05:41:14

Python中所寻找的不存在。

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

酒中人 2025-02-01 05:41:14

这应该减少打字。关键是dict构造函数,而不是文字声明语法{}

#can also use outside vars
d = 4

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

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,
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文