[Tutor] why use *get*

A.M. Kuchling amk@amk.ca
Wed Aug 6 17:10:17 2003


On Fri, Aug 01, 2003 at 10:15:06AM -0300, Luiz Siqueira Neto wrote:
> d = {'name':'foo'}
> 
> ### all this instructions have the same result
> d['name'] = d.get('name', 0) + 'bar'

.get() makes a difference when you're accessing a key that *isn't* in the 
dictionary; in that case it returns the value of its second argument.

d['title'] raises a KeyError exception.
d.get('title', 'Untitled') returns the string "Untitled".

This is useful when you want to get a value from a dictionary but
don't want to crash if the key isn't there, e.g. if processing
e-mails, you don't want to stop with a KeyError if a message lacks a
'Subject' header.

--amk
Things are getting out of control; even *I* can't play this many games at once!
      -- The Doctor, in "Ghost Light"