You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit d95f719
Browse filesBrowse the repository at this point in the historyBrowse files
.. 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
+
35
38
Dictionary Constructors
36
39
-----------------------
37
40
@@ -41,7 +44,7 @@ The dict "literal":
41
44
42
45
.. code-block:: python
43
46
44
-
# This dict "lie"
47
+
# This dict "lies"
45
48
>>> {'key1': 3, 'key2': 5}
46
49
{'key1': 3, 'key2': 5}
47
50
@@ -64,12 +67,13 @@ Calling the dict type object constructor:
64
67
>>> d
65
68
{'key1': 3, 'key2': 5}
66
69
70
+
67
71
Dictionary Indexing
68
72
-------------------
69
73
70
74
And how do you get stuff out (index it)?
71
75
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:
73
77
74
78
.. code-block:: python
75
79
@@ -83,7 +87,7 @@ The same way you index a sequence, except the index (now called a key) can be al
83
87
>>> d[0]
84
88
'zero'
85
89
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:
87
91
88
92
.. code-block:: python
89
93
@@ -93,12 +97,13 @@ What if the key doesn't exist in the dict?
93
97
KeyError: 'non-existing key'
94
98
95
99
100
+
96
101
What can keys be?
97
102
-----------------
98
103
99
104
Surely not ANYTHING?
100
105
101
-
Not quite: keys can be any immutable:
106
+
Not quite: keys can be any "immutable":
102
107
103
108
* number
104
109
* string
@@ -122,12 +127,14 @@ Actually -- any "hashable" type.
122
127
123
128
So, technically, it's not mutability, but hashability that matters.
124
129
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.
126
131
127
132
Hashing
128
133
-------
129
134
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).
131
138
132
139
They always return the same proxy for the same input.
133
140
@@ -150,7 +157,7 @@ The access time is constant regardless of the size of the dict.
150
157
Dictionary indexing
151
158
-------------------
152
159
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.
154
161
155
162
Key to value:
156
163
@@ -180,7 +187,7 @@ Traditionally, dictionaries have had no defined order. See this example from Pyt
180
187
181
188
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.
182
189
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
184
191
Dec 15, 2017 <https://mail.python.org/pipermail/python-dev/2017-December/151283.html>.
185
192
186
193
.. code-block:: ipython
@@ -215,6 +222,9 @@ and ``dict.popitem()`` will remove the "last" item in the dict.
215
222
216
223
**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.
217
224
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.
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.
251
261
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())
253
267
254
268
255
269
dict keys and values
@@ -271,15 +285,15 @@ Iterating on everything
271
285
Dictionary Performance
272
286
-----------------------
273
287
274
-
* indexing is fast and constant time: O(1).
288
+
* Indexing is fast and constant time: O(1).
275
289
276
-
* ``x in s`` constant time: O(1).
290
+
* ``x in s`` is fast and constant time: O(1).
277
291
278
-
* visiting all is proportional to n: O(n).
292
+
* Visiting all items is proportional to n: O(n).
279
293
280
-
* inserting is constant time: O(1).
294
+
* Inserting is constant time: O(1).
281
295
282
-
* deleting is constant time: O(1).
296
+
* Deleting is constant time: O(1).
283
297
284
298
285
299
http://wiki.python.org/moin/TimeComplexity
@@ -327,7 +341,7 @@ But you can specify a default:
327
341
In [11]: d.get('something', 'a default')
328
342
Out[11]: 'a default'
329
343
330
-
never raises an Exception (default is None).
344
+
`get()` never raises an Exception (default is None).
331
345
332
346
333
347
iterating
@@ -341,7 +355,7 @@ iterating
341
355
this
342
356
that
343
357
344
-
Which is equivalent to, but faster than:
358
+
Which is equivalent to, but a bit faster than:
345
359
346
360
.. code-block:: ipython
347
361
@@ -351,7 +365,9 @@ Which is equivalent to, but faster than:
351
365
this
352
366
that
353
367
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:
355
371
356
372
.. code-block:: ipython
357
373
@@ -361,6 +377,16 @@ But to get values, you must specify you want values:
361
377
5
362
378
7
363
379
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
+
364
390
365
391
``pop()``
366
392
---------
@@ -387,11 +413,16 @@ pop out an arbitrary key, value pair
387
413
In [24]: d
388
414
Out[24]: {}
389
415
416
+
note that it's the last item, so not completely arbitrary.
417
+
418
+
``setdefault``
419
+
--------------
420
+
390
421
This one is handy:
391
422
392
423
``setdefault(key[, default])``
393
424
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.
395
426
396
427
.. code-block:: ipython
397
428
@@ -411,7 +442,10 @@ The next time you call it, it gets the already set value:
411
442
Out[7]: 'a value'
412
443
413
444
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.
415
449
416
450
And dicts are mutable -- so be careful!
417
451
@@ -445,15 +479,25 @@ If you want a copy, use the explicit copy method to get a copy:
445
479
In [54]: item_copy
446
480
Out[54]: {'something': 'a value', 'something else': 'another value'}
447
481
482
+
or pass any mapping into the dict constructor::
483
+
484
+
.. code-block:: python
485
+
486
+
new_dict =dict(old_dict)
487
+
488
+
448
489
449
490
Sets
450
491
====
451
492
452
-
``set`` is an unordered collection of distinct values.
493
+
a ``set`` is an unordered collection of distinct values.
@@ -524,6 +568,47 @@ All the "set" operations from math class...
524
568
525
569
s.symmetric_difference( other, ...)
526
570
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
+
527
612
Frozen Set
528
613
----------
529
614
@@ -599,6 +684,15 @@ The "standard" way:
599
684
for key insorted(d.keys()):
600
685
...
601
686
687
+
As dicts DO preserve order, you can make a sorted version of a dict:
**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``.
0 commit comments