Python 2.7之前dict理解的替代方案
如何使以下功能与早于Python 2.7的Python版本兼容Python 2.7之前dict理解的替代方案,python,dictionary,python-2.x,python-2.6,dictionary-comprehension,Python,Dictionary,Python 2.x,Python 2.6,Dictionary Comprehension,如何使以下功能与早于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])} 使用: 这是带有生成器表达式的dict()函数,生成(键、值)对 或者,通俗地说,是对形式的直接理解: {key_expr: valu
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])}
使用:
这是带有生成器表达式的dict()
函数,生成(键、值)
对
或者,通俗地说,是对形式的直接理解:
{key_expr: value_expr for targets in iterable <additional loops or if expressions>}
{key\u expr:value\u expr for targets in iterable}
始终可以使用以下命令使其与Python<2.7兼容:
dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)
dict((键expr,值expr)用于iterable中的目标)
我想第二个与Python=2.7兼容?如果不是,我通常会尝试为这两个版本提供一个健壮的版本,但我不认为我能捕捉到语法错误。@kvoth此答案中的语法是向前兼容的,适用于Python 2.4和更新版本(包括所有Python 3.x版本)。
dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)