Home > Mobile >  Is there any way to check if a value near a certain value is in the keys of the dictionary?
Is there any way to check if a value near a certain value is in the keys of the dictionary?

Time:06-03

I need to check if a value is near a certain value in the keys of the dictionary. For example, I have a dictionary temp below and there are 4 keys; 1,10,20,30. If I code like this, it makes sense.

temp = {1:2, 10:4, 20:5, 30:12}
10 in temp.keys()
>> True

15 in temp.keys()
>> False

But if I code like this, it shows the result that I didn't anticipate. Becase x 1 is 10 and this value is certainly in the keys of the dictionary.

x = 9
(x-2 or x-1 or x or x 1 or x 2) in temp.keys()
>>False

Did I miss something? I wonder how to solve this. Please help me Thanks

CodePudding user response:

You could use any:

>>> temp = {1: 2, 10: 4, 20: 5, 30: 12}
>>> x = 9
>>> any(val in temp.keys() for val in (x - 2, x - 1, x, x   1, x   2))
True
>>> any(x   dx in temp.keys() for dx in range(-2, 2   1))
True
>>> any(val in temp.keys() for val in range(x - 2, x   3)))
True

CodePudding user response:

Input: 1 or 2 or 3
Output: 1

Input: 1 and 2 and 3
Output: 3

As you can see from the example above. or gives the first value and and gives the last value.

Issue you have is because of the line:

(x-2 or x-1 or x or x 1 or x 2)

This line does not acts as the boolean expression. Instead it gives you whatever the value of x - 2 is. In your case it will be 7. And 7 is not in the key. So, it's False.

  • Related