How to check if a key-value pair is present in a dictionary?


Is there a smart pythonic way to check if there is an item (key,value) in a dict?


b in a:
--> True
c in a:
--> False
Asked By: Peter



Use the short circuiting property of and. In this way if the left hand is false, then you will not get a KeyError while checking for the value.

>>> a={'a':1,'b':2,'c':3}
>>> key,value = 'c',3                # Key and value present
>>> key in a and value == a[key]
>>> key,value = 'b',3                # value absent
>>> key in a and value == a[key]
>>> key,value = 'z',3                # Key absent
>>> key in a and value == a[key]
Answered By: Bhargav Rao

You can check a tuple of the key, value against the dictionary’s .items().

test = {'a': 1, 'b': 2}
print(('a', 1) in test.items())
>>> True
Answered By: Morgan Thrapp

You’ve tagged this 2.7, as opposed to 2.x, so you can check whether the tuple is in the dict’s viewitems:

(key, value) in d.viewitems()

Under the hood, this basically does key in d and d[key] == value.

In Python 3, viewitems is just items, but don’t use items in Python 2! That’ll build a list and do a linear search, taking O(n) time and space to do what should be a quick O(1) check.

Answered By: user2357112
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'a': 1}
>>> c = {'a': 2}

First here is a way that works for Python2 and Python3

>>> all(k in a and a[k] == b[k] for k in b)
>>> all(k in a and a[k] == c[k] for k in c)

In Python3 you can also use

>>> b.items() <= a.items()
>>> c.items() <= a.items()

For Python2, the equivalent is

>>> b.viewitems() <= a.viewitems()
>>> c.viewitems() <= a.viewitems()
Answered By: John La Rooy

Using get:

# this doesn't work if `None` is a possible value
# but you can use a different sentinal value in that case
a.get('a') == 1

Using try/except:

# more verbose than using `get`, but more foolproof also
a = {'a':1,'b':2,'c':3}
    has_item = a['a'] == 1
except KeyError:
    has_item = False


Other answers suggesting items in Python3 and viewitems in Python 2.7 are easier to read and more idiomatic, but the suggestions in this answer will work in both Python versions without any compatibility code and will still run in constant time. Pick your poison.

Answered By: eestrada
   a.get('a') == 1
=> True
   a.get('a') == 2
=> False

if None is valid item:

{'x': None}.get('x', object()) is None
Answered By: GingerPlusPlus

Converting my comment into an answer :

Use the dict.get method which is already provided as an inbuilt method (and I assume is the most pythonic)

>>> dict = {'Name': 'Anakin', 'Age': 27}
>>> dict.get('Age')
>>> dict.get('Gender', 'None')

As per the docs –

get(key, default) –
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method
never raises a KeyError.

Answered By: letsc

Using .get is usually the best way to check if a key value pair exist.

if my_dict.get('some_key'):
  # Do something

There is one caveat, if the key exists but is falsy then it will fail the test which may not be what you want. Keep in mind this is rarely the case. Now the inverse is a more frequent problem. That is using in to test the presence of a key. I have found this problem frequently when reading csv files.


# csv looks something like this:

# now the code
import csv
with open('path/to/file', 'r') as fh:
  reader = csv.DictReader(fh) # reader is basically a list of dicts
  for row_d in reader:
    if 'b' in row_d:
      # On the second iteration of this loop, b maps to the empty string but
      # passes this condition statement, most of the time you won't want 
      # this. Using .get would be better for most things here. 
Answered By: Dan

For python 3.x
use if key in dict

See the sample code

mylist = [a, b, c]
for obj in mylist:
    if 'b' in obj:

Output: 2
Answered By: IRSHAD
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.