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
a.get('a') == 1
=> True
a.get('a') == 2
=> False
if None
is valid item:
{'x': None}.get('x', object()) is None
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
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
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
:
# 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.
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