How to test if a key in a dictionary exists?

John Machin sjmachin at lexicon.net
Mon Mar 12 00:49:50 EDT 2007


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]
>>>

Cheers,
John




More information about the Python-list mailing list