30

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
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Peter
  • 1,629
  • 2
  • 25
  • 45

9 Answers9

37

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
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
11

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
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
10

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
5
>>> 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
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
4

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.

letsc
  • 2,515
  • 5
  • 35
  • 54
1

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.

eestrada
  • 1,575
  • 14
  • 24
0
   a.get('a') == 1
=> True
   a.get('a') == 2
=> False

if None is valid item:

{'x': None}.get('x', object()) is None
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
0

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. 
Dan
  • 1,874
  • 1
  • 16
  • 21
0

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
IRSHAD
  • 2,855
  • 30
  • 39