python - 有没有一种惯用的方法来建立一个以变量名作为键,值作为值的字典?

标签 python dictionary

是否有一种惯用的(也许更像 pythonic)方法来处理这个问题:

title = "my title"
name = "my name"
# [... on and on ...]

my_dict = {
    'title': title,
    'name': name,
    # and on and on
}

基本上,变量名(编码)是键,变量值是值吗?

最佳答案

在 Python 中,对象没有名字,也不知道它们的名字。因此,给定 title,您无法推断出字符串 "title"

作用域(globalslocalsvars)将名称关联到对象,所以任何此类 hack 都必须经过范围。一种方法是:

title = "my title"
name = "my name"

things_I_want = "title", "name"
scope = vars()
{name: scope[name] for name in things_I_want}
#>>> {'title': 'my title', 'name': 'my name'}

当然,这是不受欢迎的。正确的做法是走很长的路。

关于python - 有没有一种惯用的方法来建立一个以变量名作为键,值作为值的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25944853/

相关文章:

python - 如果只有一列,为什么 Pandas Transform 会失败

java - 按值对 AtomicLongMap 进行排序

python - 反转字典并显示值

python - 使用 scipy 的 trapz 函数进行积分

python - 使用 aggfunc 时出现 pandas InvalidIndexError

python - GAE 上的 jinja2 在每次响应时写出 'None'

c# - OrderedDictionary 和字典

python - 如何在列表理解中将字典值转换为小写?

python - 递归遍历多维字典并导出为csv

python - 过滤掉python pandas中两个百分位数之间的数据