Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 862
Ben Avatar asked Jan 23 '09 14:01

Ben


People also ask

How do you check if a given key already exists in a dictionary?

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.

How do you increment a dictionary?

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.

How do you check if a value is already in a dictionary?

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.

Can we repeat the values of Key in 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.


2 Answers

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 
like image 194
dF. Avatar answered Sep 27 '22 00:09

dF.


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.

like image 42
Andrew Wilkinson Avatar answered Sep 25 '22 00:09

Andrew Wilkinson