How to get min key value pair in hash
Asked Answered
W

4

7

I want to fetch the lowest value in the hash.

Input:

test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03, 'f' => 0.02, 'g'=> 0.1}

Expected result:

{'f'=> 0.02}

How can I get the expected result?

I need all minimum key/value pairs. if {'a'=>1,'b'=>1,'c'=>2} the expected result should be {'a'=>1,'b'=>1}.

Weinert answered 5/6, 2014 at 11:33 Comment(2)
What do you want to do if there are multiple minimum values?Favin
i need all minimum key/value pairs. if {'a'=>1,'b'=>1,'c'=>2}. the expected result is {'a'=>1,'b'=>1}Weinert
Q
15
[test.min_by{|k, v| v}].to_h


Answer to the question after it has been changed:
test.group_by{|k, v| v}.min_by{|k, v| k}.last.to_h # => {"f"=>0.02}

or

test.group_by(&:last).min_by(&:first).last.to_h # => {"f"=>0.02}
Quitt answered 5/6, 2014 at 11:40 Comment(0)
R
10
test.select { |_, v| v == test.values.min }

To make it more efficient:

min_val = test.values.min
test.select { |_, v| v == min_val }
Ragwort answered 5/6, 2014 at 11:46 Comment(0)
R
0

AS Per Given Your Data

Run the following on your Ruby Console :-

test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03,
'f' => 0.02, 'g'=> 0.1}

Hash[*test.sort_by(&:last)[0]]

Output will be as per per your expectations

 => {"f"=>0.02} 
Rummage answered 5/6, 2014 at 12:48 Comment(1)
REVIEW of low quality post: Please format your code better. Write some explanation of proposed solution as well. In the current form this answer is likely to be deleted for moderation reasons. I'm not voting for deletion only because it seems to be a good path to solve the problem. Someone else might not be so generous.Clostridium
T
0

You can also achieve this without using a .min method:

def min_key_value_pair (test)
  if test == {}
       return nil
  else
       test = test.sort_by {|k, v| v}
       test[0]
   end
end

I had to do something similar for a class I am taking. We also had to return JUST THE KEY. for which you would do the same thing only return test[0][0] Hope this was helpful!!!

Tav answered 28/6, 2017 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.