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.
Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
Method #1 : Using get() The get function can be used to initialize a non-existing key with 0 and then the increment is possible. By this way the problem of non-existing key can be avoided.
To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.
Keys in a dictionary can only be used once. If it is used more than once, as you saw earlier, it'll simply replace the value.
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
I prefer to do this in one line of code.
my_dict = {} my_dict[some_key] = my_dict.get(some_key, 0) + 1
Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With