Skip to content

Commit 69cfad0

Browse files
authored
gh-116488: Mention dict.get in the data structures tutorial (GH-139643)
1 parent b73aaff commit 69cfad0

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

Doc/tutorial/datastructures.rst

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -512,8 +512,12 @@ dictionary; this is also the way dictionaries are written on output.
512512
The main operations on a dictionary are storing a value with some key and
513513
extracting the value given the key. It is also possible to delete a key:value
514514
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.
517521

518522
Performing ``list(d)`` on a dictionary returns a list of all the keys
519523
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::
528532
{'jack': 4098, 'sape': 4139, 'guido': 4127}
529533
>>> tel['jack']
530534
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
531541
>>> del tel['sape']
532542
>>> tel['irv'] = 4127
533543
>>> tel

0 commit comments

Comments
 (0)