Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to dict comprehension prior to Python 2.7

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])} 
like image 431
stdcerr Avatar asked Jan 12 '14 00:01

stdcerr


People also ask

Is there a similar comprehension syntax for set and dictionary comprehensions?

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.

Should I use dict () or {}?

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.

Is there dictionary comprehension in Python?

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.

Is dictionary comprehension faster than for loop?

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.


1 Answers

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>) 
like image 171
Martijn Pieters Avatar answered Oct 05 '22 17:10

Martijn Pieters