Luke Taylor Luke Taylor - 6 months ago 6x
Python Question

Check for the presence of a key/value pair in a Python dictionary

What is the shortest way to check for the existence of a certain key/value pair in a dictionary if I don't know that the key exists?

So far, I've come up with:

if 'key' in my_dict and my_dict['key'] == 'value':

This is really long with longer variable names or longer key/value names, such as:

if 'X-Powered-By' in self.request.headers and self.request.headers['X-Powered-By'] == 'NodeBB':

What's a shorter way to check for the presence of a key and a corresponding value?


You can fetch the value, and compare it right away:

# default return value is None if key is not found
if mydict.get("key") == "somevalue" 


# Or specify your own default value
if mydict.get("key", False) == "somevalue"

Check out Python dict.get docs.