在Python中查找字典值的最小值

2024-07-03 07:37:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在不使用python中的min()函数的情况下找到dictionary第二个元素的min。必须是一个循环

例如,我的dictionary

sol = {"shape1":[250, 300, 280], "shape2":[46, 70, 5], 
       "shape3":[147, 12, 150], "shape4":[107, 10, 108]}

我应该得到的输出是shape2,因为第一个值低于另一个shape第一个值

任何帮助都是必要的

谢谢


Tags: 函数元素dictionary情况minshapesolshape1
2条回答

一个使用dict值的sorted的线性

sol= {"shape1":[250, 300, 280], 
    "shape2":[46, 70, 5], 
    "shape3":[147, 12, 150], 
    "shape4":[107, 10, 108]}

[(k) for k, v in sorted(sol.items(), key=lambda item: item[1][0])][0] # 'shape2'

试试这个:

sol = {"shape1":[250, 300, 280], "shape2":[46, 70, 5], "shape3":[147, 12, 150], "shape4":[107, 10, 108]}

smallest_shape = ""
smallest_value = 0
for i, pair in enumerate(sol.items()):
    if i == 0 or pair[1][0] < smallest_value:
        smallest_shape = pair[0]
        smallest_value = pair[1][0]

print(smallest_shape)

相关问题 更多 >