[Tutor] why use *get*

Michael Janssen Janssen@rz.uni-frankfurt.de
Fri Aug 1 10:18:02 2003


On Fri, 1 Aug 2003, Luiz Siqueira Neto wrote:

> I don't know why use *get*.
>
> ex.
> d =3D {'name':'foo'}
>
> ### all this instructions have the same result
> d['name'] =3D d.get('name', 0) + 'bar'
> d['name'] =3D d.get('name', 1) + 'bar'
> d['name'] =3D d.get('name', 2) + 'bar'
> d['name'] =3D d.get('name', 3) + 'bar'
> d['name'] =3D +=3D 'bar'

PYTHONDOC/lib/typesmapping.html:
a.get(k[, x]) ---> a[k] if k in a, else x

since your dictionary d has a key "name" the default values 0; 1; 2 and 3
arn't used (otherwise would raise TypeError: unsupported operand type(s)
for +: 'int' and 'str'). d.get('name', 0) returns the value of d['name']
in this case. d.get('not_a_key_of_d', 0) returns 0.

> For what I use *x.get* ????

to avoid having to write (example made with a 'counter'):

if d.has_key('counter'):
   d['counter'] +=3D 1
else:
   d['counter'] =3D 1

# or
try: d['counter'] +=3D 1
except KeyError: d['counter'] =3D 1

Note that the later one isn't aquivalent to d.get() in terms of
internal behavior (effect is =E4quivalent). First example is =E4quivalent
to d.get(). Nevertheless use of d.get() might help you to write
cleaner code (because lesser levels of indentation).

regards
Michael