2

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?

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
begs
  • 151
  • 7

2 Answers2

2

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
Alexander
  • 88
  • 5
1

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.

Maximouse
  • 4,170
  • 1
  • 14
  • 28