Logo

Programming-Idioms

  • Clojure
  • Python

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.

from operator import itemgetter
for x in sorted(mymap.items(), key=itemgetter(1)):
    print(x)
for x in sorted(mymap, key=mymap.get):
    print(x, mymap[x])
import operator
for key, value in sorted(d.items(), key=operator.itemgetter(1)):
    print(key, value)

operator.itemgetter(1) gets the second item in the tuple returned by d.items()
for x, k in sorted((x, k) for k,x in mymap.items()):
    print(k, x)
for_each(begin(mymap), end(mymap),
    [&s](const auto& kv) { s.insert(kv.second); });

Using a std::multiset<>

New implementation...