Skip to content

Commit d95f719

Browse files
updated dicts and sets with set operators
1 parent 72b0d58 commit d95f719

1 file changed

Lines changed: 117 additions & 23 deletions

File tree

‎source/modules/DictsAndSets.rst‎

Lines changed: 117 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ for a dict, you do::
3232

3333
item = stuff["third"]
3434

35+
.. note:: It is *very* common to use strings as keys in a dictionary. So common that virtually all examples you'll see both here and on the Internet use strings as keys. And many other languages have similar objects that only allow strings (like JavaScript objects, for instance). Python dicts, on the other hand, can use many types as keys, and this can be a very powerful feature to keep in mind.
36+
37+
3538
Dictionary Constructors
3639
-----------------------
3740

@@ -41,7 +44,7 @@ The dict "literal":
4144

4245
.. code-block:: python
4346
44-
# This dict "lie"
47+
# This dict "lies"
4548
>>> {'key1': 3, 'key2': 5}
4649
{'key1': 3, 'key2': 5}
4750
@@ -64,12 +67,13 @@ Calling the dict type object constructor:
6467
>>> d
6568
{'key1': 3, 'key2': 5}
6669
70+
6771
Dictionary Indexing
6872
-------------------
6973

7074
And how do you get stuff out (index it)?
7175

72-
The same way you index a sequence, except the index (now called a key) can be all kinds of stuff:
76+
The same way you index a sequence, except the index (now called a key) can be various types, rather than just an integer:
7377

7478
.. code-block:: python
7579
@@ -83,7 +87,7 @@ The same way you index a sequence, except the index (now called a key) can be al
8387
>>> d[0]
8488
'zero'
8589
86-
What if the key doesn't exist in the dict?
90+
What if the key doesn't exist in the dict? You get a ``KeyError`` exception:
8791

8892
.. code-block:: python
8993
@@ -93,12 +97,13 @@ What if the key doesn't exist in the dict?
9397
KeyError: 'non-existing key'
9498
9599
100+
96101
What can keys be?
97102
-----------------
98103

99104
Surely not ANYTHING?
100105

101-
Not quite: keys can be any immutable:
106+
Not quite: keys can be any "immutable":
102107

103108
* number
104109
* string
@@ -122,12 +127,14 @@ Actually -- any "hashable" type.
122127

123128
So, technically, it's not mutability, but hashability that matters.
124129

125-
(Athough for most intents and purposes, you want to use immutable types as keys in dicts.)
130+
Although for most intents and purposes, you want to use immutable types as keys in dicts.
126131

127132
Hashing
128133
-------
129134

130-
Hash functions convert arbitrarily large data to a small proxy (usually an int).
135+
What does "hashable" mean? (https://computersciencewiki.org/index.php/Hashing)
136+
137+
Hash functions convert arbitrarily large data to a small proxy (usually an integer).
131138

132139
They always return the same proxy for the same input.
133140

@@ -150,7 +157,7 @@ The access time is constant regardless of the size of the dict.
150157
Dictionary indexing
151158
-------------------
152159

153-
Note: cPython name look-ups are implemented with the dicts -- it's highly optimized.
160+
Note: cPython name look-ups are implemented with dicts -- it's highly optimized.
154161

155162
Key to value:
156163

@@ -180,7 +187,7 @@ Traditionally, dictionaries have had no defined order. See this example from Pyt
180187
181188
Note how I defined the dict in a natural order, but when it gets printed, or you display the keys, they are in a different order.
182189

183-
However, In cPython 3.6, the internal implementation was changed, and it *does* happen to preserve order. In cPython 3.6, that is considered an implementation detail -- and you should not count on it! However, as of cPython 3.7, dictionaries preserving order will be part of the language specification. This was declared by Guido on the python-dev mailing list on
190+
However, In cPython 3.6, the internal implementation was changed, and it *does* happen to preserve order. In cPython 3.6, that is considered an implementation detail -- and you should not count on it! However, as of cPython 3.7, dictionaries preserving order are part of the language specification. This was declared by Guido on the python-dev mailing list on
184191
Dec 15, 2017 <https://mail.python.org/pipermail/python-dev/2017-December/151283.html>.
185192

186193
.. code-block:: ipython
@@ -215,6 +222,9 @@ and ``dict.popitem()`` will remove the "last" item in the dict.
215222

216223
**CAUTION** This is new behavior in cPython 3.6 -- older versions of Python (notably including Python 2) do not preserve order. In older versions, there is a special version of a dict in the collections module: ``collections.OrderedDict`` which preserves order in all versions of Python, and has a couple extra features.
217224

225+
Also: while Python dicts now *preserve* order, they are not really a fully ordered object: there is no direct way to get, say, the "third" item in a dict, or to inset an item at a particular location.
226+
227+
218228

219229
Dictionary Iterating
220230
--------------------
@@ -247,9 +257,13 @@ dict keys and values
247257
In [28]: d.items()
248258
Out[28]: dict_items([('name', 'Brian'), ('score', 42)])
249259
250-
Notice that these are of type ``dict_keys`` and ``dict_values``. These are special types that provide iteration, printing and other features, but are tied to the underlying dict, rather than copies.
260+
Notice that these are of type ``dict_keys`` and ``dict_values``. These are special types that provide iteration, printing and other features, but are tied to the underlying dict, rather than copies. They are actually Sets (see below), so can be compared to sets, and the ``in`` operator is efficient.
251261

252-
(Python2 would simply create lists of keys and values -- but then you were making a copy when you probably didn't need one).
262+
(Python2 would simply create lists of keys and values -- but then you were making a copy when you probably didn't need one). If you do need a copy, or a proper Sequence, simmply wrap them in a ``list()``:
263+
264+
.. code-block:: python
265+
266+
the_values_as_a_list = list(a_dict.values())
253267
254268
255269
dict keys and values
@@ -271,15 +285,15 @@ Iterating on everything
271285
Dictionary Performance
272286
-----------------------
273287

274-
* indexing is fast and constant time: O(1).
288+
* Indexing is fast and constant time: O(1).
275289

276-
* ``x in s`` constant time: O(1).
290+
* ``x in s`` is fast and constant time: O(1).
277291

278-
* visiting all is proportional to n: O(n).
292+
* Visiting all items is proportional to n: O(n).
279293

280-
* inserting is constant time: O(1).
294+
* Inserting is constant time: O(1).
281295

282-
* deleting is constant time: O(1).
296+
* Deleting is constant time: O(1).
283297

284298

285299
http://wiki.python.org/moin/TimeComplexity
@@ -327,7 +341,7 @@ But you can specify a default:
327341
In [11]: d.get('something', 'a default')
328342
Out[11]: 'a default'
329343
330-
never raises an Exception (default is None).
344+
`get()` never raises an Exception (default is None).
331345

332346

333347
iterating
@@ -341,7 +355,7 @@ iterating
341355
this
342356
that
343357
344-
Which is equivalent to, but faster than:
358+
Which is equivalent to, but a bit faster than:
345359

346360
.. code-block:: ipython
347361
@@ -351,7 +365,9 @@ Which is equivalent to, but faster than:
351365
this
352366
that
353367
354-
But to get values, you must specify you want values:
368+
In fact, there are very few things you can do with the ``dict_keys`` that you can't do directly with the dict.
369+
370+
But to get values, you must specify you want the values:
355371

356372
.. code-block:: ipython
357373
@@ -361,6 +377,16 @@ But to get values, you must specify you want values:
361377
5
362378
7
363379
380+
and to get both, you use ``.items``:
381+
382+
.. code-block:: ipython
383+
384+
In [4]: for item in d.items():
385+
...: print(item)
386+
...:
387+
('this', 5)
388+
('that', 7)
389+
364390
365391
``pop()``
366392
---------
@@ -387,11 +413,16 @@ pop out an arbitrary key, value pair
387413
In [24]: d
388414
Out[24]: {}
389415
416+
note that it's the last item, so not completely arbitrary.
417+
418+
``setdefault``
419+
--------------
420+
390421
This one is handy:
391422

392423
``setdefault(key[, default])``
393424

394-
gets the value if it's there, sets it if it's not.
425+
gets the value if it's there, sets it to the specified default if it's not. Returns the value in either case.
395426

396427
.. code-block:: ipython
397428
@@ -411,7 +442,10 @@ The next time you call it, it gets the already set value:
411442
Out[7]: 'a value'
412443
413444
414-
Assignment is a link to the original dict, just like lists or anything else.
445+
Assignment
446+
----------
447+
448+
Assignment (with ``=``) is a link to the original dict, just like lists or anything else. Remember that assignment is simply binding a new name to something.
415449

416450
And dicts are mutable -- so be careful!
417451

@@ -445,15 +479,25 @@ If you want a copy, use the explicit copy method to get a copy:
445479
In [54]: item_copy
446480
Out[54]: {'something': 'a value', 'something else': 'another value'}
447481
482+
or pass any mapping into the dict constructor::
483+
484+
.. code-block:: python
485+
486+
new_dict = dict(old_dict)
487+
488+
448489
449490
Sets
450491
====
451492

452-
``set`` is an unordered collection of distinct values.
493+
a ``set`` is an unordered collection of distinct values.
453494

454-
Essentially a set is a dict with only keys.
495+
Essentially, a ``set`` is a dict with only keys.
496+
497+
https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset
455498

456499
Set Constructors:
500+
-----------------
457501

458502
.. code-block:: ipython
459503
@@ -524,6 +568,47 @@ All the "set" operations from math class...
524568
525569
s.symmetric_difference( other, ...)
526570
571+
Set Operators
572+
-------------
573+
574+
All the basic set operations are support with math-class like operators:
575+
576+
Test whether every element in the set is in other::
577+
578+
set <= other
579+
580+
581+
Test whether the set is a proper subset of other, that is, set <= other and set != other::
582+
583+
set < other
584+
585+
Test whether every element in other is in the set::
586+
587+
set >= other
588+
589+
Test whether the set is a proper superset of other, that is, ``set >= other and set != other``::
590+
591+
set > other
592+
593+
Union: Return a new set with elements from the set and all others::
594+
595+
set | other | ...
596+
597+
Intersection: Return a new set with elements common to the set and all others::
598+
599+
set & other & ...
600+
601+
Difference: Return a new set with elements in the set that are not in the others::
602+
603+
set - other - ...
604+
605+
Symmetric difference: return a new set with elements in either the set or other but not both::
606+
607+
set ^ other
608+
609+
In fact, it is the operator versions that make the ``set`` object "officially" a Set: (`Set ABC <https://docs.python.org/3.8/library/collections.abc.html?highlight=set%20abc#collections.abc.Set>`_)
610+
611+
527612
Frozen Set
528613
----------
529614

@@ -599,6 +684,15 @@ The "standard" way:
599684
for key in sorted(d.keys()):
600685
...
601686
687+
As dicts DO preserve order, you can make a sorted version of a dict:
688+
689+
.. code-block:: python
690+
691+
sorted_dict = dict(sorted(dict.items(), key=sort_key))
692+
693+
where sort_key is a function that takes the (key, value) tuple and returns a value to sort on.
694+
695+
602696
Another option:
603697

604698
.. code-block:: python
@@ -609,5 +703,5 @@ Also other nifty stuff in the ``collections`` module:
609703

610704
https://docs.python.org/3.6/library/collections.html
611705

612-
**NOTE:** In Python 3.6, dicts were optimized in a way that happens to preserve order. But this is considered an implementation detail. Do not count on it! If you want order preserved, use OrderedDict.
706+
**NOTE:** As of Python 3.6, dicts do preserve order. But they are not full featured ordered objects. If you want a "properly" ordered object, use ``OrderedDict``.
613707

0 commit comments

Comments
 (0)