How to test if a key in a dictionary exists?

Alex Martelli aleax at mac.com
Mon Mar 12 05:19:05 CET 2007


Paul McGuire <ptmcg 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.


Alex



More information about the Python-list mailing list