Alternative to dict comprehension prior to Python 2.7

风格不统一 提交于 2019-11-26 01:36:25

问题


How can I make the following functionality compatible with versions of Python earlier than Python 2.7?

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:


Use:

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

That's the dict() function with a generator expression producing (key, value) pairs.

Or, to put it generically, a dict comprehension of the form:

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

can always be made compatible with Python < 2.7 by using:

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


来源:https://stackoverflow.com/questions/21069668/alternative-to-dict-comprehension-prior-to-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!