My Ordered Dict is not working as I expected

94 views Asked by At

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?

1

There are 1 answers

0
paxdiablo On BEST ANSWER
key_tall = max(person.keys())
key_short = min(person.keys())

Your keys are the integers 0..9 so it's expected that you'll get 9 and 0 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:

indexes_tall = [idx for idx in range(len(person)) if person[idx] == max(person.keys())]

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:

from collections import OrderedDict as OD
person = OD({})

for num in range(10):
    person[num] = float((num + 1) % 10) # effectively your input

tall = max(person.values())
short = min(person.values())

keys_tall = [str(idx + 1) for idx in range(len(person)) if person[idx] == max(person.keys())]
keys_short = [str(idx + 1) for idx in range(len(person)) if person[idx] == min(person.keys())]

print(f'The shortest height of {short}m is held by: {" ".join(keys_short)}')
print(f'The tallest height of {tall}m is held by: {" ".join(keys_tall)}')

will give you:

The shortest height of 0.0m is held by: 10
The tallest height of 9.0m is held by: 9