Peter
Peter

Reputation: 1669

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

Upvotes: 30

Views: 81237

Answers (9)

eestrada
eestrada

Reputation: 1603

Using get:

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

Using get with a unique sentinel:

# With a custom sentinel as the default value, `None` 
# should only be returned if `None` is the actual
# value in the key/value pair.
_unique_sentinel = object()
a.get('a', _unique_sentinel) == None

Using try/except:

# more verbose than using simple `get` without sentinel value
# 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.

Upvotes: 1

IRSHAD
IRSHAD

Reputation: 2933

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

Upvotes: 0

Dan
Dan

Reputation: 1884

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

Upvotes: 0

letsc
letsc

Reputation: 2567

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.

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304137

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

Upvotes: 6

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

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

if None is valid item:

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

Upvotes: 0

user2357112
user2357112

Reputation: 280310

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.

Upvotes: 10

Morgan Thrapp
Morgan Thrapp

Reputation: 9986

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

Upvotes: 11

Bhargav Rao
Bhargav Rao

Reputation: 52071

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

Upvotes: 38

Related Questions