TDictionary in Delphi

How to Use TDictionary in Delphi

TDictionary Generics Collection is used to store hash table type collection of key pairs in Delphi. It is an example of Delphi Generics Collection. These generic types were introduced in Delphi 2009 and allow you to define classes that don’t specifically define various data member types.


TDictionary in Delphi
TDictionary in Delphi


A dictionary is somehow similar to an array, having a series of values that is indexed by an integer or ordinal type value.


In Delphi Software, the TDictionary is also defined as a hash table. Hash tables, in turn, represent a collection of key-and-value pairs that are organized based on the key’s hash code. When a key-value pair is added to the table, the hash of that key is computed and stored along with the key-pair, where it is also optimized for lookups.



Steps in Using Delphi’s TDictionary

  1. Declare our dictionary by specifying the TKey and TValue types by adding this string:


dict : TDictionary;


By using the Add Method, you can fill in the dictionary details. To remove a valued pair, use the Remove method. The TryGetValue can be used to check if there are some key value pairs included in the dictionary.


  1. Since it is a hash table, the dictionary does not automatically sort its items in order. You can do the sorting by means of TList, another generic collections type that has a sorting feature. The code can sort ascending and descending keys and grabs values in the dictionary in a sorted order. Key Values uses TComparer and an anonymous method to do the descended sorting.


Take note, however, that TObjectDictionary has the capability to automatically handle objects for a lifetime. The Value’s value can be set to null but the Key’s value cannot. As an addition, Ownerships Parameter specifies whether the dictionary owns the keys, values or both, therefore helping you to prevent memory leaks.