How to test if a key in a dictionary exists?

mensanator at aol.com mensanator at aol.com
Mon Mar 12 15:43:31 EDT 2007


On Mar 11, 11:49 pm, "John Machin" <sjmac... at lexicon.net> wrote:
> On Mar 12, 3:19 pm, a... at mac.com (Alex Martelli) wrote:
>
> > Paul McGuire <p... at austin.rr.com> wrote:
> > > will be.  For instance, when working with data from 0 to 100 and
> > > looking for frequencies by decade, you can initialize the histogram-
> > > dict with:
>
> > > for i in range(10):
> > >     histodict[i] = 0
>
> > A better way, of course (also saving the histodict = {} which you didn't
> > mention but surely intended) would be:
>
> >     histodict = dict.fromkeys(range(10), 0)
>
> > In Python, in general, the more conceptually compact, direct, simple and
> > higher-abstraction approach tends to be faster as well, BTW.
>
> That's so true, especially if it's matched to the problem space, isn't
> too new, and doesn't need looking up in the docs :-)
>
> Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
> win32
> Type "copyright", "credits" or "license" for more information.>>> histodict = dict.fromkeys(range(10), 0)
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'dict' is not defined>>> histolist = [0] * 10
> >>> histolist[3] += 1
> >>> histolist
>
> [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]

In defense of my original if:else: idiom, I'll point
out that there may be more to be done when the key is
absent than simply creating a new one and initializing it.

Also, a dictionary doesn't need an integer index, so I can
create bins such as '2.01','2.02',etc.

And in some cases, it's not known what the range of the
keys will be making it difficult to pre-allocate the list.

And yes, the empty buckets will need to be created for
graphing purposes, but that can be done after the test
has completed so that the only empty buckets that need
be created are those between the outliers.

>
>
>
> Cheers,
> John





More information about the Python-list mailing list