Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the key of the largest value hash?

Tags:

ruby

hash

People also ask

How do you find the maximum value in a hash table?

There is no built in function to get the maximum value out of a Hashtable you are going to have to loop over all the keys and manually determine the max. Show activity on this post.

What is a key value hash?

A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.

Does hash have a key?

Hash functions like SHA-* do not need a key, they just calculate a hash-value from any input. There are other functions like HMAC, which indeed use a key, together with a hash function.

Where is hash key stored?

The hash of a key is always turned into an index in the array.


This will return max hash key-value pair depending on the value of hash elements:

def largest_hash_key(hash)
  hash.max_by{|k,v| v}
end

I found this way , return the key of the first max value

hash.key(hash.values.max)

Another way could be as follows:

hash.each { |k, v| puts k if v == hash.values.max }

This runs through each key-value pair and returns (or in this case puts's) the key(s) where the value is equal to the max of all values. This should return more than one key if there's a tie.


If you want to retrieve more than one key value pair based on order(second largest, smallest etc.), a more efficient way will be to sort the hash once and then get the desired results.

def descend_sort(hash)
   hash = hash.sort_by {|k,v| v}.reverse
end

Key of largest value

puts *hash[0][0]

Get max and min

puts *hash[0], *hash[hash.length-1]

2nd largest key value pair

Hash[*hash[1]]

To convert the hash array back into a hash

hash.to_h

You can use the select method if you want the key value pair returned:

hash.select {|k,v| v == hash.values.max }

I did this today on a similar problem and ended up with this:

hash = { "CA"=>2, "MI"=>1, "NY"=>1 }

hash.invert.max&.last
=> "CA" 

For Ruby less than 2.3 you can replace &.last with .try(:last) Either one is just a safeguard for if your source hash is empty: {}