Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.

for x, k in sorted((x, k) for k,x in mymap.items()):
    print(k, x)
from operator import itemgetter
for x in sorted(mymap.items(), key=itemgetter(1)):
    print(x)
import operator
for key, value in sorted(d.items(), key=operator.itemgetter(1)):
    print(key, value)
for x in sorted(mymap, key=mymap.get):
    print(x, mymap[x])
for_each(begin(mymap), end(mymap),
    [&s](const auto& kv) { s.insert(kv.second); });
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 std.algorithm;
import std.array;
mymap.byKeyValue
     .array
     .sort!((a, b) => a.value < b.value)
     .each!(p => writeln(p.key, " ", p.value));
mymap.entries.toList()
    ..sort((a, b) => a.value.compareTo(b.value))
    ..forEach(print);
mymap 
|> Map.to_list 
|> Enum.sort(fn ({_k1, val1}, {_k2, val2}) -> val1 <= val2 end)
|> Enum.each(fn ({k, v}) -> IO.puts("#{k}: #{v}") end)
import "fmt"
import "sort"
type entry struct {
	key   string
	value int
}

type entries []entry
func (list entries) Len() int { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] }

entries := make(entries, 0, len(mymap))
for k, x := range mymap {
	entries = append(entries, entry{key: k, values: x})
}
sort.Sort(entries)

for _, e := range entries {
	fmt.Println("Key =", e.key, ", Value =", e.value)
}
import "fmt"
import "sort"
type entry struct {
	key   string
	value int
}

entries := make([]entry, 0, len(mymap))
for k, x := range mymap {
	entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool {
	return entries[i].value < entries[j].value
})

for _, e := range entries {
	fmt.Println("Key =", e.key, ", Value =", e.value)
}
import Data.Map as Map
import Data.List (sortBy)
import Data.Ord (comparing)
mapM_ print $ sortBy (comparing snd) $ Map.toList mymap
import Data.Map as Map
import Data.List (sortOn)
mapM_ print . sortOn snd $ Map.toList mymap
Object.entries(mymap)
  .sort((a, b) => a[1] - b[1])
  .forEach(([key, value]) => {
    console.log('key:', key, 'value:', value);
  });
import static java.lang.System.out;
import static java.util.Map.Entry.comparingByValue;
mymap.entrySet()
    .stream()
    .sorted(comparingByValue())
    .forEach(out::println);
import static java.util.Map.Entry.comparingByValue;
mymap.entrySet()
    .stream()
    .sorted(comparingByValue())
    .forEach(e -> {
        K k = e.getKey();
        X x = e.getValue();
    });
import java.util.Comparator;
import java.util.Map;
mymap.entrySet().stream()
    .sorted(Comparator.comparing(Map.Entry::getValue))
    .forEach(entry -> {
        K k = entry.getKey();
        X x = entry.getValue();
        System.out.println("k:" + k + ", x:" + 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";
}

for my $k (sort {($mymap{$a}<=>$mymap{$b}) or ($a cmp $b)}
           keys %mymap) {
   print "$k: $mymap{$k}\n";
}
dict_pairs(D, _, Ps),
transpose_pairs(Ps, TPs),
keysort(TPs, Val_sorted),
forall(member(V-K, Val_sorted),
       format("~w:~w~n", [V, K]))
mymap.sort_by{|k,x| x}.each{|k,x| puts "#{k}: #{x}"}
let mut items: Vec<_> = mymap.iter().collect();
items.sort_by_key(|item| item.1);
for (k, x) in items {
    println!("[{},{}]", k, x);
}
use itertools::Itertools;
for (k, x) in mymap.iter().sorted_by_key(|x| x.1) {
	println!("[{},{}]", k, x);
}

New implementation...
< >
programming-idioms.org