Simplest way to create an array from an associative array which its contains keys and values?

bearophile bearophileHUGS at lycos.com
Fri Jan 3 09:47:41 PST 2014


Gary Willoughby:

> Simplest way to create an array from an associative array which 
> its contains keys and values?
>
> For example if i have an associative array like this:
>
> ["one":"1", "two":"2"]
>
> What's the easiest way to create a dynamic array that looks 
> like this:
>
> ["one", "1", "two", "2"]
>
> I know it can be done via a loop, but is there a more idiomatic 
> way to achieve this?

Unfortunately the D associative arrays specs don't specify this 
to be correct:

zip(aa.byKey, aa.byValue)


So a solution without foreach loops is:

void main() {
     import std.stdio, std.algorithm, std.array;

     auto aa = ["one":"1", "two":"2"];
     string[] r = aa.byKey.map!(k => [k, aa[k]]).join;
     r.writeln;
}


You can also use joiner if you need just a lazy range.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list