If Dict Contains a particular key
John Nagle
nagle at animats.com
Thu Apr 26 02:56:17 EDT 2007
mensanator at aol.com wrote:
> On Apr 24, 1:41 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
>
>>Steven Howe wrote:
>>
>>>Carsten Haese wrote:
>>>
>>>>On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote:
>>
>>>>>Hello Guys,
>>
>>>>>I'm Looking to build a quick if/else statement that checks a
>>>>>dictionary for a key like follows.
It would be useful if there was some direct way to get the value
associated with a key, and None if there's not one.
The basic options are
if dict.has_key(key} :
value = dict[key]
else :
value = None
or
try:
value = dict[key]
except:
value = None
one of which requires two lookups, and the other of which takes
you through the exception machinery.
This can be a bottleneck in some text processing applications.
But it's not a big deal.
John Nagle
More information about the Python-list
mailing list