I can't believe it, but I've been stumped by what should be a very simple task.
I need to check if a value is in a dictionary as either key or value. I can find keys using if 'A' in dictionary
, however I can't seem to get this to work for values
. I realise I could use a for loop to do this and I may resort to this but I was wondering if there is a built in method for it.
You can use in
operator and any
function like this
value in dictionary or any(value in dictionary[key] for key in dictionary)
Here, value in dictionary
makes sure that the expression is evaluated to be Truthy if the value
is one of the keys of dictionary
any(value in dictionary[key] for key in dictionary)
This part makes sure that, the value
being searched is in any of the values in the dictionary.
Note: This approach is very efficient because
you don't have to create any additional list in the memory
any
function short circuits, immediately after finding a match.
If you want to make sure that the value being searched should be exactly matched, then you can change the in
to ==
like this
value in dictionary or any(value == dictionary[key] for key in dictionary)
As DSM Suggested, it would be better if we use value in dict.itervalues()
in Python 2.x, value in dict.values()
in Python 3.x
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