How to test if a key in a dictionary exists?

Paul McGuire ptmcg at austin.rr.com
Sun Mar 11 09:40:06 CET 2007


On Mar 10, 9:12 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> > if hist.has_key(outcome):
> >     hist[outcome] += 1  # if key already exists, increment
> > else:
> >     hist[outcome] = 1   # else create a new key
>
> You could write that:
>
>    hist[outcome] = 1 + hist.get(outcome, 0)
>
> Or with Python 2.5 you could use
>
>    hist = defaultdict(int)
>    ...
>    hist[outcome] += 1  # automatically initializes to 0 if outcome not found

Often when building a histogram, one knows in advance what the keys
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

and then just update the appropriate bucket without having to do any
testing at all:

fibSeqUpTo100 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for val in fibSeqUpTo100:
    key = val/10
    histodict[ key ] += 1

This has the added benefit of including entries for the empty buckets
as well.

-- Paul




More information about the Python-list mailing list