在Python 2.7之前替代dict理解

std*_*err 33 python syntax dictionary 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])}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 65

使用:

gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))
Run Code Online (Sandbox Code Playgroud)

这是dict()生成(key, value)对的生成器表达式的函数.

或者,一般来说,一个字母理解形式:

{key_expr: value_expr for targets in iterable <additional loops or if expressions>}
Run Code Online (Sandbox Code Playgroud)

始终可以通过使用以下方式与Python <2.7兼容:

dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)
Run Code Online (Sandbox Code Playgroud)