Comprehension to find the min in a dict

前端 未结 6 1182
鱼传尺愫
鱼传尺愫 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:21

    I know this code works with O(1):

    car_value = list(car_dict.values())

    This is incorrect. To form a list from a view you must iterate over all values. This operation will have time complexity of O(n).

    In general, creating a list of keys and values is not necessary. Avoid these operations as they are expensive.

    Note that min can work directly on dict.items, which is a view of key-value pairs. This is only advisable if you only have a single car with the minimum value:

    car, value = min(car_dict.items(), key=lambda x: x[1])  # (fiat, 100)
    

    Since dictionaries are not considered ordered (unless you are using Python 3.7), for duplicate minima the result will not be certain. In this case, you can calculate the minimum value and then use a list comprehension:

    min_val = min(car_dict.values())
    min_cars = [car for car, value in car_dict.items() if value == min_val]  # ['fiat']
    

    You can also use next with a generator expression to extract the first such car:

    min_car_first = next(car for car, value in car_dict.items() if value == min_val)
    

    Of course, in the case of a single car with the minimum value, this will give the same result as the first solution min(car_dict.items(), ...).

提交回复
热议问题