julia - How to find the key for the min/max value of a Dict?

前端 未结 4 1782
有刺的猬
有刺的猬 2021-02-20 13:57

I want to find the key corresponding to the min or max value of a dictionary in julia. In Python I would to the following:

my_dict = {1:20, 2:10}
min(my_dict, my         


        
4条回答
  •  鱼传尺愫
    2021-02-20 14:29

    If you only need the minimum value, you can use

    minimum(values(my_dict))
    

    If you need the key as well, I don't know a built-in function to do so, but you can easily write it yourself for numeric keys and values:

    function find_min_key{K,V}(d::Dict{K,V})
    
        minkey = typemax(K)
        minval = typemax(V)
    
        for key in keys(d)
            if d[key] < minval
                minkey = key
                minval = d[key]
            end
        end
    
        minkey => minval
    end
    
    my_dict = Dict(1=>20, 2=>10)
    
    find_min_key(my_dict)
    

提交回复
热议问题