Merging two dictionaries
Let's assume that we have two dictionaries that we need to merge into a single dictionary. To accomplish this, Tcl provides the dict merge
command. The syntax is as follows:
dict merge dictionaryValue1 dictionaryValue2…
How to do it…
In the following example, we will create two dictionaries containing collections of key/value pairs and then using the dict merge
command create a dictionary containing the contents of both. Return values from the commands are provided for clarity. Enter the following command:
% set test1 [dict create 1 John 2 Mary 3 Paul] 1 John 2 Mary 3 Paul % set test2 [dict create 4 Fred 5 Sue 6 Tom] 4 Fred 5 Sue 6 Tom % set merged [dict merge $test1 $test2] 1 John 2 Mary 3 Paul 4 Fred 5 Sue 6 Tom
How it works…
The dict merge
command returns a dictionary containing the contents of two or more dictionaries, as specified in the dictionaryValue
arguments. In the event of duplicate key mapping, the last dictionary merged will be the value that will be...