Alternative to dict comprehension prior to Python 2.7

stdcerr picture stdcerr · Jan 12, 2014 · Viewed 10.2k times · Source

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])}

Answer

Martijn Pieters picture Martijn Pieters · Jan 12, 2014

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>)