How do I isolate a specific key from a dictionary using greater or less than arguments on a string of values?

Question:

Just started coding; so, I am happy to clarify if there are questions.

I have a dictionary where each key is associated with a string of 2 values

my_dict = {‘KEY##’ : (X, Y)}

e.g., my_dict = {‘CAR10’ : (4, -3), ‘BAT15’ : (2, 5), ‘DOG22’ : (-2, 1)}

I would like to isolate and print out any key(s) where, for example, -1<X<3 and 3<Y<7

I’ve tried doing this using an iterative process and basic if/then statements; however, nothing I have tried has been "legal", so to speak (I always get error messages, all of them different).

Asked By: Ruth Groza

||

Answers:

I think this list comprehenshion is what you want:

my_filtered_keys = [k for (k, (x, y)) in my_dict.items() if -1<x<3 and 3<y<7]
print(my_filtered_keys)
Answered By: cafce25
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.