Sorted output from an associative array

bearophile bearophileHUGS at lycos.vom
Wed Jan 30 08:19:37 PST 2013


FG:

> Let's say i have an array: int[string] wordCount.

That's an associative array, and it's unsorted just like a Python 
dict.

In Phobos there is a sorted tree, if you want, that keeps keys 
sorted.


> How to print key:value pairs ordered by descending value?

There are various solutions. A simple solution is to use a 
foreach to create an array of 2-tuples (key,value), and then use 
a schwartzsort to sort just according to values.


> Or generally how to to store wordCount in an array of structs 
> or type tuples for later sorting?

You don't use type tuples for that, just Phobos tuples.
This code is not fast because it appends (untested):


Tuple!(string, int)[] items;
foreach (k, v; wordCount)
     items ~= tuple(k, v);
items.schwartzSort!(it => it[1], "a < b")();


> In Python I would use something like this:
> sorted(wordCount.items(), key=lambda a: a[1], reverse=True).

In Python you use key=itemgetter(1). And in Python2 you use 
iteritems() for that.

Unfortunately in D there is no byPair() because that ties 
druntime with std.typecons...

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list