Is there a single method or easy way how to copy one TDictionary content into another ? Let's say I have the following declarations
type
TItemKey = record
ItemID: Integer;
ItemType: Integer;
end;
TItemData = record
Name: string;
Surname: string;
end;
TItems = TDictionary<TItemKey, TItemData>;
var
// the Source and Target have the same types
Source, Target: TItems;
begin
// I can't find the way how to copy source to target
end;
and I would like to copy 1:1 the Source to Target. Is there such method for this ?
Thanks!
The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.
Copy a dictionary with a for loop To copy a dictionary it is also possible to use a for loop: >>> d1 = {'a':1,'b':2} >>> d2 = {} >>> for key in d1: ... d2[key] = d1[key] ...
The simplest way to create a copy of a Python dictionary is to use the . copy() method. This method returns a shallow copy of the dictionary.
TDictionary has a constructor that allows you to pass in another collection object, which will create the new one by copying the contents of the original. Is that what you are looking for?
constructor Create(Collection: TEnumerable<TPair<TKey,TValue>>); overload;
So you would use
Target := TItems.Create(Source);
And Target would be created as a copy of Source (or at least contain all the items in Source).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With