Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'if in' with a dictionary

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.

like image 250
Harvey Avatar asked Dec 02 '22 16:12

Harvey


1 Answers

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

  1. you don't have to create any additional list in the memory

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

like image 107
thefourtheye Avatar answered Dec 10 '22 13:12

thefourtheye