Python 2.7 之前的 dict 理解的替代方案

Posted

技术标签:

【中文标题】Python 2.7 之前的 dict 理解的替代方案【英文标题】:Alternative to dict comprehension prior to Python 2.7 【发布时间】:2014-01-30 22:08:35 【问题描述】:

如何使以下功能与 Python 2.7 之前的 Python 版本兼容?

gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log]      
gw_func_dict = chr(2**i): func for i, func in enumerate(gwfuncs[:8])

【问题讨论】:

【参考方案1】:

用途:

gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))

这就是 dict() 函数,它带有生成 (key, value) 对的生成器表达式。

或者,通俗地说,是对形式的 dict 理解:

key_expr: value_expr for targets in iterable <additional loops or if expressions>

始终可以通过以下方式与 Python

dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)

【讨论】:

我猜第二个兼容Python=2.7?如果不是,我通常会使用 try 为两者获得一个健壮的版本,但我认为我无法捕捉到语法错误。 @Kvothe 此答案中的语法是前向兼容的,适用于 Python 2.4 及更高版本(包括所有 Python 3.x 版本)。

以上是关于Python 2.7 之前的 dict 理解的替代方案的主要内容,如果未能解决你的问题,请参考以下文章

Python 2.7中的无内存泄漏OrderedDict替代方案?

Python字典增量

在Javascript中是否有python 2.7x中的Object spread语法?

为啥在 Python 2.7 中两级字典的值都指向同一个对象?

Python 2.7 列表理解泄漏变量名 [重复]

在 CMD 中“python”启动 Python 3.3,“py”启动 Python 2.7,我该如何更改?