34

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])}
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
stdcerr
  • 13,725
  • 25
  • 71
  • 128

1 Answers1

67

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>)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I guess the second one is compatible with both Python<2.7 and Python>=2.7? If not I would usually use try to get a robust version for both but I don't think I can catch the Syntax Error. – Kvothe Feb 11 '21 at 18:19
  • @Kvothe the syntax in this answer is forward-compatible and works on Python 2.4 and newer (including all Python 3.x releases). – Martijn Pieters Feb 11 '21 at 22:55