I would like to optimize this statement:
if 'key' in dictionary and dictionary['key']!=value:
Is there a way to check if a key exists in a dictionary and check the value at the same time?
I would like to optimize this statement:
if 'key' in dictionary and dictionary['key']!=value:
Is there a way to check if a key exists in a dictionary and check the value at the same time?
Use the .get()
dict method, which returns None
if the key is not in the dictionary instead of throwing a KeyError exception:
d = {'a':0,'b':1}
if d.get('a')==0:
# you will enter this if-statement
if d.get('c')==0:
# you will not enter this if-statement and will not throw a KeyError
Python dict
has a get()
method. For example, if d
is a dict, d.get(x, y)
returns d[x]
if it exists, otherwise it returns y
. This means that your if statement can be replaced with if dictionary.get(key, value) != value
.