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.
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 dict
s, 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