Comprehension to find the min in a dict

前端 未结 6 1187
鱼传尺愫
鱼传尺愫 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 06:01

    How about this:

    car_dict = {'mercedes': 200, 'fiat': 100, 'porsche': 300, 'rocketcar': 600}
    min_car = {}
    for car in car_dict:
        if not min_car or car_dict[car] < min_car['speed']:
            min_car['name'] = car
            min_car['speed'] = car_dict[car]
    print(min_car)
    

提交回复
热议问题