Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a hash by value when it has many keys

Tags:

sorting

hash

perl

I believe this is how you would normally sort a hash by value:

foreach my $key (sort { $hash{$a} <=> $hash{$b} } (keys %hash) ) {
    print "$key=>$hash{$key}";
}

This would print out the values smallest to largest.

Now, what if I have a hash like this:

$hash{$somekey}{$somekey2}{$thirdkey}

How could I sort by values and get all the keys as well?

like image 891
petranaya Avatar asked Aug 19 '11 20:08

petranaya


People also ask

How does hash sort by key value?

If you want to access a Hash in a sorted manner by key, you need to use an Array as an indexing mechanism as is shown above. This works by using the Emmuerator#sort_by method that is mixed into the Array of keys. #sort_by looks at the value my_hash[key] returns to determine the sorting order.

Can hashes be sorted?

The hash sort is a general purpose non-comparison based sorting algorithm by hashing, which has some interesting features not found in conventional sorting algorithms. The hash sort asymptotically outperforms the fastest traditional sorting algorithm, the quick sort.

How do I sort hash hash in Perl?

For example we can sort the hash first by the Position value, and among the entries with the same Position value we can sort by the value of the Max field. In order to do this we will use the following expression: my @maxed = sort { $data->{$a}{Position} <=> $data->{$b}{Position}

Can you sort elements in a ruby hash object?

Sorting Hashes in Ruby To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.


Video Answer


1 Answers

I would just create a new hash:

my %new;
for my $k1 (keys %hash) {
  for my $k2 (keys %{$hash{$k1}}) {
    for my $k3 (keys %{$hash{$k1}{$k2}}) {
      $new{$k1,$k2,$k3} = $hash{$k1}{$k2}{$k3};
    }
  }
}

my @ordered = sort { $new{$a} <=> $new{$b} } keys %new;
for my $k (@ordered) {
  my @keys = split($;, $k);
  print "key: @k      - value: $new{$k}\n";
}
like image 200
ErikR Avatar answered Nov 06 '22 21:11

ErikR