How to get all the values by keys that is within a range?

Question:

I have a dictionary:

dict = {8.12: 4, 6.93: 2, 6.78: 2, 7.04: 2, 7.21: 2, 8.05: 4, 7.48: 2, 
        6.52: 0, 6.95: 2, 7.28: 2, 7.56: 2, 6.67: 0, 6.33: 2, 6.37: 1, 
        7.15: 1, 8.16: 5, 7.84: 3, 7.13: 2, 6.24: 0, 7.11: 3}

I want to get all the values by key that is in range +- 1. For example, how can I get all that values that the key value is between 7 and 9.

x = 8
print dict[range(x-1,x+1)]
Asked By: user11398251

||

Answers:

something like:

for key in dict.keys():
    if key >= x-1 and key <= x+1:
        print dict[key]

Answered By: Nicolas
print [dict[i] for i in dict.keys() if i > x-2 and i < x+2]

enter image description here

Answered By: CodeByAk

Using comprehenssion, in a pythonic way :

x=8
print([dict[key] for key in dict if x+1 >= key >= x-1])
Answered By: Kaushal Pahwani
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.