Logo

Programming-Idioms

  • VB
  • C#
  • Haskell
  • Pascal
  • Perl

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Multiple entries may exist for the same value x.

sub by_val_then_key {
    return ($mymap{$a} <=> $mymap{$b})
        or ($a cmp $b)
}

for my $k (sort by_val_then_key keys %mymap) {
   print "$k: $mymap{$k}\n";
}

Create a custom, reusable sort routine and use it by name.
Assuming the keys are strings, we use <=> to compare the numeric values, and cmp to use the lexical order of the key as a tie breaker.
for my $k (sort {($mymap{$a}<=>$mymap{$b}) or ($a cmp $b)}
           keys %mymap) {
   print "$k: $mymap{$k}\n";
}

For a one-off, put the comparison in a code block.
Assuming the keys are strings, we use <=> to compare the numeric values, and cmp to use the lexical order of the key as a tie breaker.
using System.Collections.Generic;
using System.Linq;
Dictionary<String, String> mymap = new Dictionary<String, String>();
  
foreach(KeyValuePair<string, string> a in mymap.OrderBy(x => x.Value))
{
  Console.WriteLine("Key = {0}, Value = {1}", a.Key, a.Value);
}
import Data.Map as Map
import Data.List (sortBy)
import Data.Ord (comparing)
mapM_ print $ sortBy (comparing snd) $ Map.toList mymap

Map.toList gives a list of all (key,value) pairs. Sorts on the values (second item of the pairs) and prints.

$ is apply operator and serves here only to save parentheses.
import Data.Map as Map
import Data.List (sortOn)
mapM_ print . sortOn snd $ Map.toList mymap

Using Map.toList to convert the map to a list of (key, value) pairs, then sort the list based on the second element of the pair with sortOn snd.
for_each(begin(mymap), end(mymap),
    [&s](const auto& kv) { s.insert(kv.second); });

Using a std::multiset<>

New implementation...