Comprehension to find the min in a dict

前端 未结 6 1185
鱼传尺愫
鱼传尺愫 2021-01-25 05:19

I am curious about a thing:

I have a dict, for example with a car as key and a value regarding its speed. Now, I want to find the key with the lowest value.



        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 05:58

    The thing is you shouldn't solve this problem with a comprehension because you can't do assignment in a comprehension. Iterating the dictionary you can find the minimum in a single pass:

    car_iterator = iter(car_dict.items())
    slowest_car, min_speed = next(car_list)
    for car, speed in car_iterator:
        if speed < min_speed:
            slowest_car = car
    

提交回复
热议问题