Problem scenario
In Python if you test if a value is in a dictionary, does it look at the keys, the values, or both?
For example, you have code like this:
good_kv = {}
good_kv["a"] = 1
good_kv["b"] = 2
good_kv["c"] = 3
if "b" in good_kv:
print("The value is in the dictionary!")
else:
print("The value is not in the dictionary!")
print ("testing keys of dictionary above and values of dictionaries below")
if 3 in good_kv:
print("The value is in the dictionary!")
else:
print("The value is not in the dictionary!")
Do dictionaries keys, values or both play a role in the equivalence factor?
Solution
In the above examples, only keys are analyzed. Use .items() or .values() to incorporate the values in such for statements and subsequent coding logic. By default only the .keys() of the dictionary will play a role in "if … in" tests.
(As an aside, remember to not put quotes around integers or else they will be treated like strings.)