Python 我订购的Dict没有像我预期的那样工作

Python 我订购的Dict没有像我预期的那样工作,python,dictionary,collections,ordereddict,Python,Dictionary,Collections,Ordereddict,所以基本上我有这个代码: 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()) pr

所以基本上我有这个代码:

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')
理论上,当我把10个人放在字典里,第一个数字是1,一直到9,最后一个数字是0,结果应该是:

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


但事实上,它打印的是:

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
出于某种原因,当我的字典的值从1一直到10时,它工作得很好

关于为什么会发生这种情况以及如何解决它,有什么想法吗

key_tall = max(person.keys())
key_short = min(person.keys())
您的键是整数
0..9
,因此对于这两个值,您将得到
9
0
,因为您要求的是最小/最大键,而不考虑值

您似乎在寻找具有最高/最低值的人的密钥,但这不是代码将提供给您的

如果要查找具有最大值的项的索引,可以执行以下操作:

indexes_tall = [idx for idx in range(len(person)) if person[idx] == max(person.keys())]
这将为您提供一个和最高值匹配的索引列表,然后您可以根据需要处理这些索引。例如:

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)}')
将为您提供:

The shortest height of 0.0m is held by: 10
The tallest height of 9.0m is held by: 9
max(person.keys())
将为您提供最大密钥,而不是具有最大值的人的密钥。与
min
相同。请注意,您使用订购的ICT是否有任何特殊原因?