Skip to content Skip to sidebar Skip to footer

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? a={'a':1,'b':2,'c':3} b={'a':1} c={'a':2} b in a: --> True c in a: --> False

Solution 1:

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

Solution 2:

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

Solution 3:

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.

Solution 4:

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

Solution 5:

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.

Post a Comment for "How To Check If A Key-value Pair Is Present In A Dictionary?"