Reputation: 173
Hello all. I am studying for my cs final and dictionaries are in there. i know dictionaries well, but this one has me stumped. how would i go about solving such a question?
Given the dictionary below, continue to write code (old style, no functions required) that will produce a list of all the keys for which the values are in the range 1 to 100 inclusive. Do not hardcode your program for the given dictionary.
D = {1:1000, 2:2000, 3:3000, 1111:10, 2222:20, 3333:30}
Yes, this is an actual review question but this isn't homework.
I was thinking that I should do a for loop through the dictionary but that would not help because the dict
is stored key:value
and i really need to compare the value
only.
Anything is appreciated!
Upvotes: 0
Views: 130
Reputation: 173
i think i actually figured it out!
i didnt use comprehension because my professor never went over it for whatever reason.
d ={1:1000, 2:2000, 3:3000, 1111:10, 2222:20, 3333:30}
for key in d:
if d[key] >=1 and d[key] <=100:
print(key)
else:
pass
Upvotes: 1
Reputation: 82460
How about the following:
>>> D = {1:1000, 2:2000, 3:3000, 1111:10, 2222:20, 3333:30}
>>> [key for key in D if 1 <= D[key] <= 100]
[3333, 2222, 1111]
Upvotes: 1