Reputation: 121
I have a dictionary with keys that are iterable (1-10), and I want to find the values for a range of those keys, like from keys 3-8.
dictionary = {
1: 2.0,
2: 3.5,
3: 1.1,
4: 4.5,
5: 7.8,
6: 9.8,
7: 7.4,
8: 3.2,
9: 10.0,
10: 11.0}
for key,value in dictionary.items():
if key == 1:
print(value)
This returns 2.0
. If I try a range of values:
for key,value in dictionary.items():
if key == range(3,8):
print(value)
nothing is returned. Would I have to make an elif
statement for each value that I want returned or would it make more sense to 'flip' the keys/values and use a range of values to search for keys instead?
Upvotes: 0
Views: 503
Reputation: 81594
Assuming the range
of possible keys is smaller than the number of key-value pairs in the dict, it would be cleaner (and faster) to iterate over the possible keys rather than over the entire dict
.
for possible_key in range(3, 8):
print(dictionary.get(possible_key, 'missing value'))
Upvotes: 1