Categories
dictionary python

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

326

How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there’s already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

1

  • 12

    Small code nitpick: the code sets my_dict[key] to 1 if there’s already something there, and increments it if there isn’t. I think you want ==, not !=.

    Jun 23, 2016 at 17:20

353

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

5

  • 8

    According to his example, it should be enough to set “defaultdict(lambda: 0)” and skip the entire “if” clause.

    – Deestan

    Jan 23, 2009 at 14:57

  • This works, but confuses keys and values (making it somewhat odd to read). ‘some_value’ should be ‘some_key’

    Nov 17, 2009 at 11:42

  • @nailer: fixed, thanks. I had initially used ‘some_value’ since that’s the variable name in the question, but I agree it’s clearer now.

    – dF.

    Nov 18, 2009 at 1:11

  • 25

    …or for regular dicts, you can do my_dict[key] = my_dict.get(key, 0) + 1.

    – minmaxavg

    Jun 12, 2016 at 8:19

  • How to extend this to nested dictionaries? dict[key1][key2] += 1?

    Oct 30, 2019 at 13:44

348

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.

2

64

I personally like using setdefault()

my_dict = {}

my_dict.setdefault(some_key, 0)
my_dict[some_key] += 1

2

  • 1

    setdefault is awesome. It does not alter the value if one is already set for some_key. For example, d={1:2}; d.setdefault(1, 0) does not disturb the value of d[1].

    – wsaleem

    Oct 19, 2019 at 22:33


  • The other answers wouldn’t work but this answer did for self.site_included.setdefault(i, []) followed by self.site_included[i].append(self.post_index).

    Jan 28 at 1:45