Issue
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
Solution
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
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.