Skip to content

Commit c502865

Browse files
committed
Create not_using_a_dict_comprehension.rst.
1 parent b93992e commit c502865

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
Not using a dict comprehension
2+
==============================
3+
4+
Summary
5+
-------
6+
7+
For Python versions 2.6 and below, a common way to initialize a dict was to pass an iterable of key-value pairs in the dict's constructor (e.g. ``d = dict((key, value) for (key, value) in iterable)``). However, in Python 2.7 and beyond, a new syntax called dict comprehension (e.g. ``d = {key: value for (key, value) in iterable}``) was introduced which is generally more readable and is now the preferred style. Use the new syntax whenever possible.
8+
9+
Description
10+
-----------
11+
12+
You may encounter the old style of initializing a dict by passing an iterable of key-value pairs in older Python code that was written before version 2.7. The new dict comprehension style is functionally equivalent and is much more readable. Consider refactoring the code to use the new style, assuming that you are now using Python 2.7 or higher.
13+
14+
Examples
15+
----------
16+
17+
Not using dict comprehension
18+
............................
19+
20+
The module below demonstrates the old syntax of initializing a dict via an iterable of key-value pairs. Although there is nothing wrong with this code, it is somewhat hard to read.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
l = [1,2,3]
27+
28+
d = dict([(n,n*2) for n in l]) # hard to read
29+
30+
print d # {1: 2, 2: 4, 3: 6}
31+
32+
Solutions
33+
---------
34+
35+
Use dict comprehension
36+
......................
37+
38+
The modified module below uses the new dict comprehension syntax which was introduced in Python 2.7. Although the modified code below is functionally equivalent to the original code above, this modified module is more readable.
39+
40+
.. code:: python
41+
42+
l = [1, 2, 3]
43+
44+
d = {n: n * 2 for n in l}
45+
46+
print d # {1: 2, 2: 4, 3: 6}
47+
48+
References
49+
----------
50+
- `Stack Overflow - Create a dictionary with list comprehesion <http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension>`_

0 commit comments

Comments
 (0)