在不使用 max() 和 min() 的情况下从字典中获取最大值和最小值

Getting the max and min from a dictionary without using max() and min()

我有一个包含两个值(id 和 amount)的字典:

dict={5: [379], 11: [396], 6: [480], 19: [443]}

我想在不使用 max 和 min 函数的情况下从字典中找到具有最大和最小数量的 id。

所以期望的输出是:

max=6
min=5

python 中的字典是可迭代的,也就是说,您可以逐项浏览它们。

在这种情况下,你可以做类似的事情

for key in dict_a:
    #do something here to find the min and max
    print(key)

你可以用 for 循环计算它:

input = {5: 379, 11: 396, 6: 480, 19: 443}

keys = input.keys()
largest_key = keys[0]

for key in keys:
    if input[key] > input[largest_key]:
        largest_key = key

print(largest_key)

如果您的值是列表,则需要选择要用于与列表进行比较的索引。在下面的代码中,我硬编码为零。如果你想遍历列表并在那里找到最大值,那将只是另一个嵌套循环。

input = {5: [379], 11: [396], 6: [480], 19: [443]}

keys = input.keys()
largest_key = keys[0]

for key in keys:
    if input[key][0] > input[largest_key][0]:
        largest_key = key

print(largest_key)

要获得最小值,您将使用完全相同的过程,但将运算符切换为小于。

您可以对字典的值进行排序并访问最大和最小值,如下所示:

my_dict={5: [379], 11: [396], 6: [480], 19: [443]}


sorted_list = sorted([value for key,value in my_dict.items()])

max_val = sorted_list[-1][0]
min_val = sorted_list[0][0]

max_key = list(my_dict.keys())[list(my_dict.values()).index([max_val])]
min_key = list(my_dict.keys())[list(my_dict.values()).index([min_val])]

print(min_key, max_key)