Checking if a key is in a dict or not

So, I have P = dict()

. I have the following code:

def someFunction():
    P['key'] += 1
    '''do other task'''


What's the easiest way to check if it exists P['key']


I checked How to check if a variable exists? but I'm not sure if this answers my question.


source to share

3 answers

There are two main ways to check a normal dict:

The "watch before you jump" paradox. Of course, the else statement is not required unless you want to define some other behavior:

if 'key' in P:
    P['key'] += 1


The paradox "it's easier to ask forgiveness than permission":

    P['key'] += 1
except KeyError:
    pass  # Or do something else


Or you can use defaultdict

as suggested.



You must use defaultdict

from Collections module.

from collections import defaultdict

d = defaultdict(int)
d[0] = 5
d[1] = 10

for i in range(3):
    d[i] += 1

# Note that d[2] was not set before the loop

for k, v in d.items():
    print('%i: %i' % (k,v))



brunsgaard@archbook /tmp> python
0: 6
1: 11
2: 1




I usually check for the presence of a key with

if some_key in some_dict:
    print("do something")


Advanced usage: if you have a dictionary, key is a string, value is a list. When the key exists, you want to add the item to the list of related keys. So you can

some_dict[some_key] = some_dict.get(some_key, []) + [new_item];




All Articles