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

## Question:

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

``````a={'a':1,'b':2,'c':3}
b={'a':1}
c={'a':2}

b in a:
--> True
c in a:
--> False
``````

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]
True
>>> key,value = 'b',3                # value absent
>>> key in a and value == a[key]
False
>>> key,value = 'z',3                # Key absent
>>> key in a and value == a[key]
False
``````

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
``````

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.

``````>>> 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)
True
>>> all(k in a and a[k] == c[k] for k in c)
False
``````

In Python3 you can also use

``````>>> b.items() <= a.items()
True
>>> c.items() <= a.items()
False
``````

For Python2, the equivalent is

``````>>> b.viewitems() <= a.viewitems()
True
>>> c.viewitems() <= a.viewitems()
False
``````

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}
try:
has_item = a['a'] == 1
except KeyError:
has_item = False

print(has_item)
``````

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.

``````   a.get('a') == 1
=> True
a.get('a') == 2
=> False
``````

if `None` is valid item:

``````{'x': None}.get('x', object()) is None
``````

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')
27
>>> dict.get('Gender', 'None')
'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.

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.

Example

``````# csv looks something like this:
a,b
1,1
1,

# now the code
import csv
with open('path/to/file', 'r') as fh:
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.
``````

For python 3.x
use `if key in dict`

See the sample code

``````#!/usr/bin/python
a={'a':1,'b':2,'c':3}
b={'a':1}
c={'a':2}
mylist = [a, b, c]
for obj in mylist:
if 'b' in obj:
print(obj['b'])

Output: 2
``````
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.