How to Find the Key of the Largest Value Hash

How to find the key of the largest value hash?

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

How to find the keys of the largest values in Hash R?

Full disclosure: I authored and maintain the hash package.

Unless you have a hash with many key-value pairs and need the performance, standard R vectors with names will likely be a better solution. Here is one example:

v <- c(a = 5, b = 2, c = 3, d = 5)
names( v[ v==max(v) ] )

Native R vectors will outperform hashes until the structure grows beyond ~200 key-value pairs. (It is been a while since I benchmarked hash, vector and list lookup performance).

If a hash fits the solution, the answer by @bergant solves the OP's questions, though please understand it is rather dangerous. Converting a hash to a list and then using unlist ignores the fact that hash values are not constrained to be scalar/atomic values. They can be any R object. Consider:

 > hash(a = 1:5, b = 2, c = 3, d=5)
<hash> containing 4 key-value pair(s).
a : 1 2 3 4 5
b : 2
c : 3
d : 5

You can decide whether this is a problem for your application or not.

A simpler, higher performing and more general approach is to use the 'values' function. In the simple case where all values are scalar/atomic values, this closely mirrors @bergant's solution.

H <- hash(a = 5, b = 2, c = 3, d = 5)
val <- values(H) # Compare to `unlist(as.list(H))`
names( val[ val == max(val) ] )

Since values returns a named list rather than an unlisted, we are set up for the more general solution since we can select a value to compare from each key value pair:

H <- hash(a = 1:5, b = 2, c = 3, d=5)
val <- values(H)

# Alternate 1: Compare min from each value
val <- sapply(val, max )

# Alternate 2: Compare first element from each value
# val <- sapply(val, function(x) x[[1]])

names( val[ val == max(val) ] )

I hope that helps.

Ruby - find the key(s) of the largest value(s) of a hash

If you want all pairs, I would do something like

max = my_hash.values.max
Hash[my_hash.select { |k, v| v == max}]

How do I get the maximum value of a hash in Ruby?

I would use the max method on the values of the hash:

{a: 1, b: 2}.values.max

What is the easiest way to get a key with the highest value from a hash in Perl?

While the solution with sort:

(sort {$hash{$a} <=> $hash{$b}} keys %hash)[0]

found in some of the other answers is quite elegant, it doesn't perform as nicely as it looks. First off, the sort transforms an O(n) search search operation into an O(n log n) one. Secondly, the sort solution has n log n hash look-ups. Hash look-ups are very good for certain operations, but when working with the entire hash, look-ups will be slower than using each, keys, or values to iterate through the data structure. This is because the iterators do not need to calculate the hashes of keys, nor do they need to repeatedly walk through bins to find the values. And the overhead is not constant, but increasing as the hashes get larger.

Here are a few faster solutions:

use strict;
use warnings;

my %hash = (
small => 1,
medium => 5,
largest => 10,
large => 8,
tiny => 0.1,
);

Here is a solution using the each iterator (an O(1) operation done n times):

sub largest_value (\%) {
my $hash = shift;
keys %$hash; # reset the each iterator

my ($large_key, $large_val) = each %$hash;

while (my ($key, $val) = each %$hash) {
if ($val > $large_val) {
$large_val = $val;
$large_key = $key;
}
}
$large_key
}

print largest_value %hash; # prints 'largest'

Or a faster version that trades memory for speed (it makes a copy of the hash):

sub largest_value_mem (\%) {
my $hash = shift;
my ($key, @keys) = keys %$hash;
my ($big, @vals) = values %$hash;

for (0 .. $#keys) {
if ($vals[$_] > $big) {
$big = $vals[$_];
$key = $keys[$_];
}
}
$key
}

print largest_value_mem %hash; # prints 'largest'

Here is the performance with various hash sizes:

10 keys:              Rate largest_with_sort largest_value largest_value_mem
largest_with_sort 111565/s -- -8% -13%
largest_value 121743/s 9% -- -5%
largest_value_mem 127783/s 15% 5% --

50 keys: Rate largest_with_sort largest_value largest_value_mem
largest_with_sort 24912/s -- -37% -40%
largest_value 39361/s 58% -- -6%
largest_value_mem 41810/s 68% 6% --

100 keys: Rate largest_with_sort largest_value largest_value_mem
largest_with_sort 9894/s -- -50% -56%
largest_value 19680/s 99% -- -12%
largest_value_mem 22371/s 126% 14% --

1,000 keys: Rate largest_with_sort largest_value largest_value_mem
largest_with_sort 668/s -- -69% -71%
largest_value 2183/s 227% -- -7%
largest_value_mem 2341/s 250% 7% --

10,000 keys: Rate largest_with_sort largest_value largest_value_mem
largest_with_sort 46.5/s -- -79% -81%
largest_value 216/s 365% -- -11%
largest_value_mem 242/s 421% 12% --

As you can see, if memory isn't much of an issue, the version with internal arrays is fastest, closely followed by the each iterator, and in a distant third... sort

Getting key with maximum value in dictionary?

You can use operator.itemgetter for that:

import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]

And instead of building a new list in memory use stats.iteritems(). The key parameter to the max() function is a function that computes a key that is used to determine how to rank items.

Please note that if you were to have another key-value pair 'd': 3000 that this method will only return one of the two even though they both have the maximum value.

>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'

If using Python3:

>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'

How do I get the key associated with the maximum value of a Rust HashMap?

Iterate through all the key-value pairs in the hashmap, comparing them by the values, keeping only the key of the maximum:

use std::collections::HashMap;

fn example<K, V>(a_hash_map: &HashMap<K, V>) -> Option<&K>
where
V: Ord,
{
a_hash_map
.iter()
.max_by(|a, b| a.1.cmp(&b.1))
.map(|(k, _v)| k)
}

fn main() {
let map: HashMap<_, _> = vec![(2, 4), (1, 3), (5, 2)].into_iter().collect();
dbg!(example(&map));
}

See also:

  • How do I create a map from a list in a functional way?
  • How can min_by_key or max_by_key be used with references to a value created during iteration?

Finding the largest value in a nested hash

game_hash[:home][:players].max_by { |_name, stats| stats[:shoe] }.last[:shoe]
#=> 19


Related Topics



Leave a reply



Submit