So basically I have this code:
from collections import OrderedDict as OD
person = OD({})
for num in range(10):
person[num] = float(input())
tall = max(person.values())
short = min(person.values())
key_tall = max(person.keys())
key_short = min(person.keys())
print(f'The shortest person is the person number {key_short} who is {short}meters tall')
print(f'The tallest person is the person number {key_tall} who is {tall}meters tall')
And in theory when I put 10 people on my dictionary, being the first number 1, going all the way to 9, and the last one being 0, the output should be:
The shortest person is the person number 9 who is 0.0m meters tall
The tallest person is the person number 8 who is 9.0m meters tall
But in fact it prints:
The shortest person is the person number 0 who is 0.0m meters tall
The tallest person is the person number 9 who is 9.0m meters tall
And for some reason when the values of my dictionary go to 1 all the way to 10, it works fine.
Any ideas on why this is happening and how to fix it?
Your keys are the integers
0..9
so it's expected that you'll get9
and0
for these two values, since you're asking for the min/max key without regard to the values.You seem to be after the key of the person that has the highest/lowest value, but that's not what that code will give you.
If you're after the indexes of the items with the largest values, you can do something like:
This will give you a list of the indexes matching the highest value, which you can then process as you see fit. As one example:
will give you: