python - 从局部变量创建 python 字典的最简洁方法

标签 python dictionary

在 Objective-C 中,您可以使用 NSDictionaryOfVariableBindings 宏来创建这样的字典

NSString *foo = @"bar"
NSString *flip = @"rar"
NSDictionary *d = NSDictionaryOfVariableBindings(foo, flip)
// d -> { 'foo' => 'bar', 'flip' => 'rar' }

python中有类似的东西吗?我经常发现自己写这样的代码

d = {'foo': foo, 'flip': flip}
# or
d = dict(foo=foo, flip=flip)

做这样的事情有捷径吗?

d = dict(foo, flip) # -> {'foo': 'bar', 'flip': 'rar'}

最佳答案

不,python 中不存在此快捷方式。

但也许这就是您需要的:

>>> def test():
...     x = 42
...     y = 43
...     return locals()
>>> test()
{'y': 43, 'x': 42}

另外,python 为这些东西提供了 globals()vars() 内置函数。 查看doc .

关于python - 从局部变量创建 python 字典的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12776400/

相关文章:

python - 将字典转换为数据框,键作为列名,键的值作为数据框的列值

python - 使用 python 合并两个 csv 文件并提取有用的信息

c# - 组合 Dictionary<A,B> + Dictionary<B,C> 来创建 Dictionary<A,C>

python - Pandas DataFrame 将字典值分配列应用或映射到 MultiIndex 值的函数

python - 将十进制转换为罗马数字

python - 字典的稀疏数组 - 高效表示

python - 使用 python 保存顶部输出

python - 使用 Pandas 计算日期时间行平均值的最快方法

python - ttk进度条卡住

r - ggplot 使用 purrr map() 绘制具有多个 y 的相同 x