[docs] Backport set and dictionary comprehensions in tutorial to 2.7 (issue 16470)

fossilet at users.sourceforge.net fossilet at users.sourceforge.net
Wed Nov 14 10:09:02 CET 2012


Reviewers: berkerpeksag, ezio.melotti,


http://bugs.python.org/review/16470/diff/6577/Doc/tutorial/datastructures.rst
File Doc/tutorial/datastructures.rst (right):

http://bugs.python.org/review/16470/diff/6577/Doc/tutorial/datastructures.rst#newcode524
Doc/tutorial/datastructures.rst:524: {'r', 'd'}
I copied all of these from the default branch, not noting the repr is
different.  But this is my first time cloning the Python source code..
On 2012/11/14 09:23:23, berkerpeksag wrote:
> In 2.7.3:
> 
>     >>> a = {x for x in 'abracadabra' if x not in 'abc'}
>     >>> a
>     set(['r', 'd'])



Please review this at http://bugs.python.org/review/16470/

Affected files:
  Doc/tutorial/datastructures.rst


diff -r bb21c800cf49 Doc/tutorial/datastructures.rst
--- a/Doc/tutorial/datastructures.rst	Mon Nov 12 20:35:29 2012 +0100
+++ b/Doc/tutorial/datastructures.rst	Wed Nov 14 14:55:09 2012 +0800
@@ -487,6 +487,10 @@
 eliminating duplicate entries.  Set objects also support mathematical operations
 like union, intersection, difference, and symmetric difference.
 
+Curly braces or the :func:`set` function can be used to create sets.  Note: To
+create an empty set you have to use ``set()``, not ``{}``; the latter creates an
+empty dictionary, a data structure that we discuss in the next section.
+
 Here is a brief demonstration::
 
    >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
@@ -513,6 +517,13 @@
    >>> a ^ b                              # letters in a or b but not both
    set(['r', 'd', 'b', 'm', 'z', 'l'])
 
+Like :ref:`for lists <tut-listcomps>`, there is a set comprehension syntax::
+
+   >>> a = {x for x in 'abracadabra' if x not in 'abc'}
+   >>> a
+   {'r', 'd'}
+
+
 
 .. _tut-dictionaries:
 
@@ -564,19 +575,18 @@
    >>> 'guido' in tel
    True
 
-The :func:`dict` constructor builds dictionaries directly from lists of
-key-value pairs stored as tuples.  When the pairs form a pattern, list
-comprehensions can compactly specify the key-value list. ::
+The :func:`dict` constructor builds dictionaries directly from sequences of
+key-value pairs::
 
    >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    {'sape': 4139, 'jack': 4098, 'guido': 4127}
-   >>> dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension
+
+In addition, dict comprehensions can be used to create dictionaries from
+arbitrary key and value expressions::
+
+   >>> {x: x**2 for x in (2, 4, 6)}
    {2: 4, 4: 16, 6: 36}
 
-Later in the tutorial, we will learn about Generator Expressions which are even
-better suited for the task of supplying key-values pairs to the :func:`dict`
-constructor.
-
 When the keys are simple strings, it is sometimes easier to specify pairs using
 keyword arguments::
 




More information about the docs mailing list