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