How to test if a key in a dictionary exists?

Paul Rubin http
Sat Mar 10 21:12:12 EST 2007


> 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



More information about the Python-list mailing list