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

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_dict.get)

Which would return the key 2.

How can I do the same in julia ?

my_dict = Dict(1=>20, 2=>10)
minimum(my_dict)

The latter returns 1=>20 instead of 2=>10 or 2.

another option is:

collect(keys(d))[indmin(collect(values(d)))]

it depends on properties of keys and values iterators which are not guaranteed, but in fact work for Dicts (and are guaranteed for OrderedDicts). like the reduce answer, d must be non-empty.

why mention this, when the reduce, pretty much nails it? it is 3 to 4 times faster (at least on my computer) !

julia - How to find the key for the min/max value of a Dict?, 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,  Method #1 : Using min() + list comprehension + values() The combination of above functions can be used to perform this particular task. In this, minimum value is extracted using the min function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with min value.

You could use reduce like this, which will return the key of the first smallest value in d:

reduce((x, y) -> d[x] ≤ d[y] ? x : y, keys(d))

This only works for non-empty Dicts, though. (But the notion of the "key of the minimal value of no values" does not really make sense, so that case should usually be handled seperately anyway.)


Edit regarding efficiency.

Consider these definitions (none of which handle empty collections)...

m1(d) = reduce((x, y) -> d[x] ≤ d[y] ? x : y, keys(d))

m2(d) = collect(keys(d))[indmin(collect(values(d)))]

function m3(d)
  minindex(x, y) = d[x] ≤ d[y] ? x : y
  reduce(minindex, keys(d))
end

function m4(d)
  minkey, minvalue = next(d, start(d))[1]
  for (key, value) in d
    if value < minvalue
      minkey = key
      minvalue = value
    end
  end
  minkey
end

...along with this code:

function benchmark(n)
  d = Dict{Int, Int}(1 => 1)
  m1(d); m2(d); m3(d); m4(d); m5(d)

  while length(d) < n
    setindex!(d, rand(-n:n), rand(-n:n))
  end

  @time m1(d)
  @time m2(d)
  @time m3(d)
  @time m4(d)
end

Calling benchmark(10000000) will print something like this:

1.455388 seconds (30.00 M allocations: 457.748 MB, 4.30% gc time)
0.380472 seconds (6 allocations: 152.588 MB, 0.21% gc time)
0.982006 seconds (10.00 M allocations: 152.581 MB, 0.49% gc time)
0.204604 seconds

From this we can see that m2 (from user3580870's answer) is indeed faster than my original solution m1 by a factor of around 3 to 4, and also uses less memory. This is appearently due to the function call overhead, but also the fact that the λ expression in m1 is not optimized very well. We can alleviate the second problem by defining a helper function like in m3, which is better than m1, but not as good as m2.

However, m2 still allocates O(n) memory, which can be avoided: If you really need the efficiency, you should use an explicit loop like in m4, which allocates almost no memory and is also faster.

Review of "maximum on dictionary returns max key instead of max , The original poster of #14672 asked for a function that would find the key of the minimum (or maximum) of the values in a dictionary. In the last  A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

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)

maximum on dictionary returns max key instead of max val · Issue , Finding the key with the maximum value on the other hand currently Dict(7=>8,​3=>6,5=>10,1=>2) julia> maximum(values(d)) 10 julia>  Now to find all the keys with maximum value, we will first use max() function to find the first key with max value like above. Then once we know the max value in dictionary then we will iterate over all the items in dictionary to find out all the keys with max value i.e.

Here is another way to find Min with Key and Value

my_dict = Dict(1 => 20, 2 =>10)

findmin(my_dict) gives the output as below

(10, 2)

to get only key use

findmin(my_dict)[2]

to get only value use

findmin(my_dict)[1]

Hope this helps.

Collections and Data Structures · The Julia Language, Dict s look for key=>value pairs, and the key is compared using isequal . is one of + , * , max , min , & , | ) when Julia can determine the neutral element of op . In Julia you can use findmax or indmax to find the index of the biggest entry in a matrix. But if you have multiple entries with this maximum value, you get the index of the first one.

Python, Given a dictionary, the task is to find the key having the maximum value. Examples : Input : {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88} Output  max always picks the first key with the max value. The dictionary could have multiple keys with that value. def keys_with_top_values(my_dict): return [key for (key, value) in my_dict.items() if value == max(my_dict.values())] Posting this answer in case it helps someone out. See the below SO post. Which maximum does Python pick in the case of a

Python, Finding min value keys in dictionary. # Using min() + list comprehension + values​(). # initializing dictionary. test_dict = { 'Gfg' : 11 , 'for' : 2 , 'CS' : 11 , 'geeks' : 8  Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument. Examples. julia> Dict([("A", 1), ("B", 2)]) Dict{String,Int64} with 2 entries: "B" => 2 "A" => 1. Alternatively, a sequence of pair arguments may be passed.

Collections and Data Structures · The Julia Language, Dict s look for (key,value) pairs, and the key is compared using isequal . Compute the minimum and maximum elements of an array over the given dimensions. To change a value assigned to an existing key (or assign a value to a hitherto unseen key): julia> dict["a"] = 10 10 Keys []. Keys must be unique for a dictionary. There's always only one key called a in this dictionary, so when you assign a value to a key that already exists, you're not creating a new one, just modifying an existing one.

Comments
  • indmin() or findmin() should work. Don't know why minimum() does the wrong thing...
  • findmin doesn't work actually; it even gives a strange result in this case: (1=>20,16)
  • @DavidP.Sanders Strange, I get (10,2).
  • @daycaster minimum iterates Pairs, which compare lexicographically. Therefore, and because here the keys are unique, minimum(x) returns the contained Pair with the lowest key. And indmin returns the index, which is different from the key.
  • There is now an issue about this in the Julia repo: github.com/JuliaLang/julia/issues/14672
  • I think it should be guaranteed that the keys and values iterator return elements in the same order. The order itself is undefined, but it'd be pretty crazy if they did something different from each other.
  • @MattB I don't think you should rely on this. As long as it's not documented, this is an implementation detail. But I agree that this should be guaranteed.
  • Let's document it, then. Care to submit a pull request?
  • This can be written without the collects, which will presumably be much faster: d.keys[indmin(values(d))]. However, d.keys is an internal data structure.
  • necroedit: As of Julia 1.0, indmin() is argmin().
  • a version without unicode and working for empty Dicts: reduce((x, y) -> (isa(x,Void) || (d[x] > d[y])) ? y : x, nothing, keys(d))
  • Very nice comparison. I like the use of next to get the first value in the dictionary, even if the syntax is not elegant!