[Tutor] get() method for dictionaries
Alan Gauld
alan.gauld at blueyonder.co.uk
Tue Mar 16 04:01:55 EST 2004
> Why do we need the get() method for dictionaries? On
> the surface, there doesn't seem to be a whole of
> difference between:
>
Try this extended example
>>> d = {}
>>> d[1] = 'one'
>>> d[1]
'one'
>>> d.get(2)
>>> d[2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 2
>>> d.get(3,'three')
'three'
>>> d[3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 3
>>>
So using get() means we don't get errors if we try to access a non
existent member and we can optionally pass a value that get returns
if the dict doesn't have one (but note it does't set that value in
the dict...)
So it means a bit less error handling in some cases.
Alan G.
More information about the Tutor
mailing list