[Tutor] Fast way to access items in a dictionary

Wayne srilyk at gmail.com
Thu Jun 18 03:33:02 CEST 2009


On Wed, Jun 17, 2009 at 7:39 PM, Elisha Rosensweig <benshafat at gmail.com>wrote:

> Hi,
>
> Till now, when I receive a dictionary that I'm not sure contains a certain
> key, I would use the following template to access a given key:
>
> if 'someKey' in dict.keys():
>    someData = dict['someKey']
>
> is there a faster way to do this? accessing a key that does not exist will
> through an exception, which is just as tiresome...


sure is:

In [97]: mydict = {'knights':'say ni', 'death':'pointy teeth'}

In [98]: mydict.get('spam')

In [99]: mydict.get('knights')
Out[99]: 'say ni'

In [100]: if mydict.get(3):
   .....:     print 'Hi'
   .....:
   .....:

In [101]: if mydict.get('death'):
   .....:     print mydict['death']
   .....:
   .....:
pointy teeth

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090617/6f9aafc1/attachment.htm>


More information about the Tutor mailing list