python / cpython

The Python programming language
https://www.python.org
Other
61.89k stars 29.77k forks source link

Python tutorial section 5.5 "It is an error to extract a value using a non-existent key." #116488

Open Dan-at-56 opened 5 months ago

Dan-at-56 commented 5 months ago

Documentation

I am a beginner in Python and also on GitHub - my apologies in advance if this is a dumb suggestion or made inappropriately...

In the Python tutorial section 5.5 on dictionaries it says: "It is an error to extract a value using a non-existent key." However, a quick test shows that an error is not generated. Rather, the value None is returned. Should the documentation be amended to that effect?

Python 3.12.2 (tags/v3.12.2:6abddd9, Feb  6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)] on win32
>>> my_dict = {'a': 1, 'b': 2, 'c': 3}
>>> value = my_dict.get('d')
>>> print(value)
None

Thanks, Dan

Dan-at-56 commented 5 months ago

I note that I do get an error if attempting to extract the value using "my_dict['d'], so the documentation is correct if it's referring only to this method of extracting a value.

terryjreedy commented 5 months ago

The point of the .get method is to avoid the exception and possibly provide a non-default default.

@rhettinger or others. Should we add a qualifier here? How about mentioning dict.get and perhaps replace a redundant example with its use. Also, I notice that 11 methods are listed for lists and none for tuple, set, and dict. Add those for the rest?

rhettinger commented 5 months ago

How about mentioning dict.get and perhaps replace a redundant example with its use.

+1 The get() method is in common use and beginners would be benefit from being introduced early.

Also, I notice that 11 methods are listed for lists and none for tuple, set, and dict. Add those for the rest?

I don't think so. The tutorial is an introduction and its easy to drown a reader in details. For dicts and sets, it is better to focus on the core operations than to explore all the methods.

sudoharshita16 commented 3 months ago

Hi @rhettinger @terryjreedy I can look into this issue.