Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4255096
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T05:10:23+00:00 2026-05-21T05:10:23+00:00

i fill a tdictionary , read from a file, to iterate over the key-value-pairs.

  • 0

i fill a tdictionary , read from a file, to iterate over the key-value-pairs. iterating was solved in delphi dictionary iterating.

the problem is that the values in the dict are not kept, probably a scope-problem with variables. i am more used to java… the values do exist directly after assigning them to the dictionary in the procedure parsetextfile, then get lost:

program parsefile;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, StrUtils, Dialogs, Generics.collections;

var key : string;
    dict: TDictionary<String, TStringlist>;
    KeysList, Valuename: TStringList;
    KeyName: string;
    i: integer;

function DeleteSpaces(str: string): string;
var
 i: Integer;
begin
 i:=0;
while i<=Length(str) do
  if str[i]=' ' then Delete(str, i, 1)
  else Inc(i);
  Result:=str;
end;

procedure HandleOneKey(KeyIndex:Integer; PrevKeys:string);
var L:TStringList;
    i:Integer;
    Part: string;
    KeyName: string;
begin
  KeyName := KeysList[KeyIndex];
  L := dict[KeyName];
  for i:=0 to L.Count-1 do
  begin
    writeln(L[i]);
    Part := KeyName + '=' + L[i];
    if KeyIndex = (KeysList.Count-1) then
      WriteLn(PrevKeys + ' ' + Part)
    else
      HandleOneKey(KeyIndex+1, PrevKeys + ' ' + Part);
  end;
end;

procedure Split(const Delimiter: Char;Input: string;const Strings: TStrings);
begin
   Strings.Clear;
   Strings.Delimiter := Delimiter;
   Strings.DelimitedText := Input;
end;

procedure parsetestfile;
  var testfile: Textfile;
      text: string;
      splitarray: TStringList;
      subsplit1, subsplit2: TStringList;
begin
  splitarray := TStringList.Create;
  subsplit1:= TStringList.Create;
  subsplit2:= TStringList.Create;
  AssignFile(testfile, 'g:\testfile.txt') ;
  Reset(testfile);

  while not Eof(testfile) do
  begin
    ReadLn(testfile, text);
    if AnsiContainsStr(text, '=') then
    begin
      Split('=', text, splitarray);
      splitarray[0] := trim(splitarray[0]);
      splitarray[1] := DeleteSpaces(splitarray[1]);
      if AnsiStartsStr('data', splitarray[0]) then
      begin
        split(' ', splitarray[0], subsplit1);
        splitarray[0]:=subsplit1[1];
        split(',', splitarray[1], subsplit2);
        dict.Add(splitarray[0], subsplit2);
        for ValueName in dict.Values do
        begin
          for i := 0 to Valuename.Count - 1 do
          write('Values are : '+ Valuename[i]);
        writeln;
        end;//for
      end;//end-data-check
    end;//end-=-check
  end;//while
  CloseFile(testfile);
  splitarray.Free;
  subsplit1.Free;
  subsplit2.Free;
end;

begin
  dict := TDictionary<String, TStringlist>.Create;
  parsetestfile;
  KeysList := TStringList.Create;

  for KeyName in dict.Keys do
    KeysList.Add(KeyName);
  for i := 0 to Keyslist.Count - 1 do
  begin
    writeln('Keylist Items: ' + Keyslist[i]);
  end;
  if KeysList.Count > 0 then
  begin
    HandleOneKey(0, '');
  end;
  dict.Destroy;
  Keyslist.Free;
  WriteLn('Press ENTER to make the window go away');
  ReadLn;
end.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T05:10:24+00:00Added an answer on May 21, 2026 at 5:10 am

    Top Edit

    I now saw you’re more used to Java, that kind of explains your problem. Java uses an Garbage Collector: if you’ve got a reference to something, that one thing is valid. Delphi doesn’t use a GC, you’re responsible for freeing all the memory you allocate. This leads to the second problem: you can free memory you’re holding a reference to, there’s nothing stopping you from doing that. In your parsetestfile procedure you’re adding subsplit2 to the dictionary, so you’re keeping a copy of that reference. Later in the same procedure you’re freeing subsplit2, so your dictionary now holds a reference to what Delphi considers to be “free memory”!

    With Delphi you need to be very careful and deliberate with life cycle management. In this case you obviously can’t free the subsplit2 in the parsetestfile procedure itself, but you do need to free it later. You’ll need to free it when you free the Dict, look at my initial code for how to do that.

    *Recom


    Here’s your code with lots of things fixed. Please read the comments, I inserted comments wherever I changed something.

    It compiles and values survive the parse procedure, but I’m not sure what you want to achieve and you forgot to provide a sample text file: I had to “make one up”.

    program Project23;
    
    {$APPTYPE CONSOLE}
    
    uses
      SysUtils, Classes, StrUtils, Dialogs, Generics.collections;
    
    var deviceid, key, topmodule : string;
        dict: TDictionary<String, TStringlist>;
        KeysList: TStringList;
        KeyName: string;
        i: integer;
    
    function DeleteSpaces(str: string): string;
    var
     i: Integer;
    begin
     i:=0;
    while i<=Length(str) do
      if str[i]=' ' then Delete(str, i, 1)
      else Inc(i);
      Result:=str;
    end;
    
    procedure HandleOneKey(KeyIndex:Integer; PrevKeys:string);
    var L:TStringList;
        i:Integer;
        Part: string;
        KeyName: string;
    begin
      KeyName := KeysList[KeyIndex];
      L := dict[KeyName];
      for i:=0 to L.Count-1 do
      begin
        writeln(L[i]);
        Part := KeyName + '=' + L[i];
        if KeyIndex = (KeysList.Count-1) then
          WriteLn(PrevKeys + ' ' + Part)
        else
          HandleOneKey(KeyIndex+1, PrevKeys + ' ' + Part);
      end;
    end;
    
    procedure Split(const Delimiter: Char;Input: string;const Strings: TStrings);
    begin
       Strings.Clear;
       Strings.Delimiter := Delimiter;
       Strings.DelimitedText := Input;
    end;
    
    procedure parsetestfile;
      var testfile: Textfile;
          text: string;
          splitarray: TStringList;
          subsplit1, subsplit2: TStringList;
          ValueName:TStringList; // Never Ever ignore compiler warnings!
          i: Integer; // Never Ever ignore compiler warnings!
    begin
      splitarray := TStringList.Create;
      subsplit1:= TStringList.Create;      
      AssignFile(testfile, 'c:\temp\testfile.txt') ;
      Reset(testfile);
    
      while not Eof(testfile) do
      begin
        ReadLn(testfile, text);
        if AnsiContainsStr(text, '=') then
        begin
          Split('=', text, splitarray);
          splitarray[0] := trim(splitarray[0]);
          splitarray[1] := DeleteSpaces(splitarray[1]);
          if AnsiStartsStr('data', splitarray[0]) then
          begin
    
            subsplit2:= TStringList.Create; // Moved the creation of subsplit2 over here, because you need one fresh list for every line of text you read.
    
            split(' ', splitarray[0], subsplit1); // can't split on SPACE because the previous split allready broke the text at "=" and at SPACE. That's how DelimitedText works!
            // splitarray[0]:=subsplit1[1]; // splitarray[0] already contains the stuff before "="; And you should check the nubmer of lines in subsplit1!
            split(',', splitarray[1], subsplit2);
            dict.Add(splitarray[0], subsplit2);
            for ValueName in dict.Values do
            begin
              for i := 0 to Valuename.Count - 1 do
              writeLN('Values are : '+ Valuename[i]); // Only use Write when you intend to write the line terminator later
            writeln;
            end;//for
          end;//end-data-check
        end;//end-=-check
      end;//while
      CloseFile(testfile);
      splitarray.Free;
      subsplit1.Free;
      // subsplit2.Free; // Ooops! You're freeing Subsplit2, after you added it as a value in the dict.
    end;
    
    begin
      dict := TDictionary<String, TStringlist>.Create;
      parsetestfile;
      KeysList := TStringList.Create;
    
      for KeyName in dict.Keys do
        KeysList.Add(KeyName);
      for i := 0 to Keyslist.Count - 1 do
      begin
        writeln('Keylist Items: ' + Keyslist[i]);
      end;
      if KeysList.Count > 0 then
      begin
        HandleOneKey(0, '');
      end;
      dict.Free; // dict.Destroy; // never call "Destroy" directly, call .Free.
      Keyslist.Free;
      WriteLn('Press ENTER to make the window go away');
      ReadLn;
    end.
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hello I want to fill an hashmap with value => key :idissue value:arraylist (list
I am trying to fill a form in a php application from a C#
What would be the best way to fill a C# struct from a byte[]
What would be the best way to fill an array from user input? Would
i am using a function to fill dictionary in a array here is the
I fill a collection one single time when my J2EE webapp starts. Then, several
When using wireframe fill mode in Direct3D, all rectangular faces display a diagonal running
I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:
I want to fill a map with class name and method, a unique identifier
Edit: I am using SqlDataAdapters to fill the data sets. Sorry--I should have been

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.