Search code examples
arraysmultidimensional-arrayd

How to create associative array of strings ( string[strings] ) from key-value file?


Here example of associative array that I would like to get:

string [string] rlist = ["dima":"first", "masha":"second", "roma":"third"];

Text file that I read have very simple structure:

peter = fourth ivan = fifth david = sixth

string [string] strarr;    
string txt = readText("test.txt");
foreach (t;txt.splitLines())
{
    // ??
}

Could anybody suggest way?


Solution

  • It may be me but I find it hard to reason about with a for loop and temp variables, I would rather do something like:

    import std.conv;
    import std.stdio;
    import std.array;
    import std.algorithm;
    
    void main() {
        string[string] dic = File("test")
                                  .byLine
                                  .map!(l => l.to!string.findSplit(" = "))
                                  .map!(l => tuple( l[0], l[2] ))
                                  .assocArray;
    }
    

    byLine: read line by line, better than reading the whole thing and then splitting.

    first map: split each line into three parts as explained by rcorre

    second map: build pairs from the splitted lines

    assocArray: build an associative array from those pairs.