Check if a given key already exists in a dictionary and increment it

Ben picture Ben · Jan 23, 2009 · Viewed 360.5k times · Source

Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?

I.e., I want to do this:

my_dict = {}

if (my_dict[key] != None):
  my_dict[key] = 1
else:
  my_dict[key] += 1

I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.

Answer

dF. picture dF. · Jan 23, 2009

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1