I run the python code with two different versions:

```
d = {}
for i in range(len(nums)):
n = nums[i]
if n in d:
prev = d[n]
if i - prev <= k:
return True
d[n] = i
return False
```

and

```
d = {}
for i in range(len(nums)):
n = nums[i]
if n in d.keys():
prev = d[n]
if i - prev <= k:
return True
d[n] = i
return False
```

The first one works but the second one exceeds time limit.

I know "n in d.keys()" will perform a linear search which makes the whole for look O(n^2).

But why does 'n in d' work?