Sorted output from an associative array

monarch_dodra monarchdodra at gmail.com
Wed Jan 30 08:22:36 PST 2013


On Wednesday, 30 January 2013 at 15:43:21 UTC, FG wrote:
> Let's say i have an array: int[string] wordCount.
> How to print key:value pairs ordered by descending value?
> Or generally how to to store wordCount in an array of structs 
> or type tuples for later sorting?
>
> In Python I would use something like this:
> sorted(wordCount.items(), key=lambda a: a[1], reverse=True).

Basically, you have to extract and sort a third party data 
structure.

what you can do is extract only the keys though, and sort them 
according to a specific pred. Then once your keys are sorted, you 
can re-obtain the value from the original AA.

Examplea addapted from TDPL:

//----
void main(string[] args)
{
     int[string] freqs = ["a":1, "b":3 , "c":2];

     // Print according to alphabet
     {
         string[] words = freqs.keys;
         sort(words);

         writeln("sorted by alphabet");
         foreach (word; words)
           writefln("%6u\t%s", freqs[word], word);
         writeln();
     }

     // Print according to frequency
     {
         string[] words = freqs.keys;
         sort!((a, b) { return freqs[a] > freqs[b]; })(words);

         writeln("sorted by frequency");
         foreach (word; words)
           writefln("%6u\t%s", freqs[word], word);
         writeln();
     }
}
//----
sorted by alphabet
      1  a
      3  b
      2  c

sorted by frequency
      3  b
      2  c
      1  a
//----


More information about the Digitalmars-d-learn mailing list