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.
Note that multiple entries may exist for the same value x.

import std.algorithm;
import std.array;
     .sort!((a, b) => a.value < b.value)
     .each!(p => writeln(p.key, " ", p.value));
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, v := range mymap {
	entries = append(entries, entry{k, v})

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)
forM_ print $ sortBy (comparing snd) $ Map.toList mymap
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]))
for x, k in sorted((x, k) for k,x in mymap.items()):
    print(k, x)
h.sort_by{|k,x| x}.each{|k,x| puts "#{k}: #{x}"}
use itertools::Itertools;
for (k, v) in map.iter().sorted_by_key(|x| x.1) {
	println!("[{},{}]", k, v);

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

Related idioms