File tree Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Original file line number Diff line number Diff line change @@ -512,8 +512,12 @@ dictionary; this is also the way dictionaries are written on output.
512
512
The main operations on a dictionary are storing a value with some key and
513
513
extracting the value given the key. It is also possible to delete a key:value
514
514
pair with ``del ``. If you store using a key that is already in use, the old
515
- value associated with that key is forgotten. It is an error to extract a value
516
- using a non-existent key.
515
+ value associated with that key is forgotten.
516
+
517
+ Extracting a value for a non-existent key by subscripting (``d[key] ``) raises a
518
+ :exc: `KeyError `. To avoid getting this error when trying to access a possibly
519
+ non-existent key, use the :meth: `~dict.get ` method instead, which returns
520
+ ``None `` (or a specified default value) if the key is not in the dictionary.
517
521
518
522
Performing ``list(d) `` on a dictionary returns a list of all the keys
519
523
used in the dictionary, in insertion order (if you want it sorted, just use
@@ -528,6 +532,12 @@ Here is a small example using a dictionary::
528
532
{'jack': 4098, 'sape': 4139, 'guido': 4127}
529
533
>>> tel['jack']
530
534
4098
535
+ >>> tel['irv']
536
+ Traceback (most recent call last):
537
+ File "<stdin>", line 1, in <module>
538
+ KeyError: 'irv'
539
+ >>> print(tel.get('irv'))
540
+ None
531
541
>>> del tel['sape']
532
542
>>> tel['irv'] = 4127
533
543
>>> tel
You can’t perform that action at this time.
0 commit comments