Creating a dictionary

To create a dictionary, we will utilize the create option. The syntax is as follows:

	dict create key value… key value… key value…

How to do it…

In the following example, we will create a dictionary containing a key/value pair. Return values from the commands are provided for clarity. Enter the following command:


% dict create 1 John
1 John

How it works…

The dict create command creates a new dictionary that contains each of the key and value mappings that follow.

There's more…

By adding additional key/value pairs on the command line, you can store numerous entries simultaneously. In the following example, we will expand our dictionary by storing multiple key/value pairs. Return values from the commands are provided for clarity. Enter the following command:


% dict create 1 John 2 Mary 3 Paul
1 John 2 Mary 3 Paul

As you can see, the dict create command accepted the arguments and created a dictionary containing our three key/value pairs. Care should be taken that the key names are not inadvertently repeated, as the last instance will be the one stored. For example, if I pass in 1 John 2 Mary 1 Paul, the value assigned to key 1 will be Paul and not

Using set with the dict create command

While the dict create command allows us to create a dictionary and easily add the key/value pairs, we have no named variable to allow us to access our dictionary. To allow us to access the dictionary, we will need to combine the Tcl set command with the dict create command to have a named dictionary that we can access.

In the following example, we will create a named dictionary containing multiple key/value pairs. The return values from the commands are provided for clarity. Enter the following command:


% set names [dict create 1 John 2 Mary 3 Paul]
1 John 2 Mary 3 Paul

While there is no noticeable difference in the return line, we now have a named dictionary that can be referenced by other commands. At this point, we can create a named dictionary and assign key/value pairs from the command line. However, without the ability to dynamically maintain our dictionary, it is of little use in a real-time program.

In the following sections, we will investigate the various Tcl commands that allow us to fully utilize the Tcl dictionary.

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

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