Comprehension to find the min in a dict

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

    well I'm not sure what is the run time of this one but you can try it it works for me :

    >>> d = {'mercedes': 200, 'fiat': 100, 'porsche': 300, 'rocketcar': 600}
    >>> d.items()
    [('mercedes', 200), ('fiat', 100), ('porsche', 300) , ('rocketcar',600)]
    >>> # find the minimum by comparing the second element of each tuple
    >>> min(d.items(), key=lambda x: x[1]) 
    ('fiat', 100)
    

提交回复
热议问题