user11398251
user11398251

Reputation: 41

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

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)]

Upvotes: 0

Views: 1276

Answers (3)

CodeByAk
CodeByAk

Reputation: 227

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

enter image description here

Upvotes: 0

Kaushal Pahwani
Kaushal Pahwani

Reputation: 474

Using comprehenssion, in a pythonic way :

x=8
print([dict[key] for key in dict if x+1 >= key >= x-1])

Upvotes: 0

Nicolas
Nicolas

Reputation: 457

something like:

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

Upvotes: 2

Related Questions