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])}
The last comprehension we can use in Python is called Set Comprehension. Set comprehensions are similar to list comprehensions but return a set instead of a list. The syntax looks more like Dictionary Comprehension in the sense that we use curly brackets to create a set.
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.
You are testing with way too small an input; while a dictionary comprehension doesn't have as much of a performance advantage against a for loop when compared to a list comprehension, for realistic problem sizes it can and does beat for loops, especially when targeting a global name.
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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With