If Dict Contains a particular key

mensanator at aol.com mensanator at aol.com
Thu Apr 26 01:30:31 EDT 2007


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.
>
> >>> If myDict contains ThisKey:
>
> >>>                 Do this...
>
> >>> Else
>
> >>>                 Do that...
>
> >> I'm pretty sure you'll find the answer to this question somewhere in
> >>http://docs.python.org/tut/tut.html
>
> >> -Carsten
>
> > or try:
> > thedict = { 'a': 1, 'b':2, 'c':3 }
> > if 'a' in thedict.keys():
> >    print thedict['a']
>
> Better yet, just:
>
>      if 'a' in thedict:
>          ...
>
> There's no need for the call to keys().

Why not

if thedict.has_key('a'):
    pass
elde:
    pass

>
> STeVe- Hide quoted text -
>
> - Show quoted text -





More information about the Python-list mailing list