[Tutor] why use *get*

Alan Gauld alan.gauld@blueyonder.co.uk
Fri Aug 1 15:39:02 2003


> d = {'name':'foo'}
> 
> ### all this instructions have the same result
> d['name'] = d.get('name', 0) + 'bar'
> d['name'] = += 'bar'
> 
> For what I use *x.get* ????

Try

print d['sex']
print d.get('sex','male')

Now do you see a difference?

get() fetches the current contents or the default provided 
if the key does not exist. Thus it never fails and causes 
an error.

HTH,

Alan G.