I want to do this:
d = {1: 2, 3: 4}
if 4 in d:
print('Aha!')
but I want to read from the values and not the keys. What's the Pythonic way to do this?
Use values1:
d = {1: 2, 3: 4}
if 4 in d.values():
print('Aha!')
Note that this will be much slower than a key lookup because it will potentially require inspecting all values in the dictionary. If you need to perform this operation often you might want to consider storing the values in a set.
1itervalues in Python 2
The nature of a dictionary is that you cannot efficiently test whether or not a value is present in the way that you can test whether a key is present.
You need to iterate over the dictionary testing each value, although this can be done transparently using the code that Mark suggests. If you have large dictionaries then performance may be an issue and you may require a different data structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With