Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting TDictionary by a key of Integer in ascending order

How can I sort TDictionary by a key of Integer in ascending order in Delphi 2009?

like image 237
Max Smith Avatar asked Jul 06 '15 22:07

Max Smith


People also ask

How do you sort a dictionary by key in ascending in Python?

First, sort the keys alphabetically using key_value. iterkeys() function. Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it. Third, sort the values alphabetically using key_value.

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

How do you sort a dictionary value in ascending order in Python?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.


1 Answers

The RTL TDictionaries are not sorted and cannot be sorted (other than by hash, which they are). You need to use another container if you wish to sort either the keys or the values. For example :

program Project1;

{$APPTYPE CONSOLE}

uses
  Generics.Collections, Generics.Defaults, SysUtils;

var
  LDict : TDictionary<integer, string>;
  i, j : integer;
  LArray : TArray<integer>;
begin
  LDict := TDictionary<integer, string>.Create;
  try
    // Generate some values
    Randomize;
    for i := 0 to 20 do begin
      j := Random(1000);
      LDict.AddOrSetValue(j, Format('The Value : %d', [j]));
    end;
    WriteLn('Disorder...');
    for i in LDict.Keys do
      WriteLn(LDict.Items[i]);
    // Sort
    LArray := LDict.Keys.ToArray;
    TArray.Sort<integer>(LArray);
    WriteLn('Order...');
    for i in LArray do
      WriteLn(LDict.Items[i]);
  finally
    LDict.Free;
  end;
  Readln;
end.
like image 84
J... Avatar answered Oct 18 '22 22:10

J...