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 used. For example, if there are two dictionaries that contain a key with different values, the second dictionary key/value mapping would be retained.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.223