user2840144
user2840144

Reputation: 173

Printing dictionary keys based on value

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

Answers (3)

user2840144
user2840144

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

Daniel Roseman
Daniel Roseman

Reputation: 599490

[k for k, v in D.items() if 1 <= v <= 100]

Upvotes: 3

Nafiul Islam
Nafiul Islam

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

Related Questions