Determining if a key exists

Now that we have a named dictionary with key/value pairs, it becomes necessary to determine if the given key exists. To accomplish this, Tcl provides the dict exists command. The syntax is as follows:

	dict exists DictionaryValue key… key…

How to do it…

In the following example, we will create a dictionary containing a set of key/value pairs and then determine whether or not a specific key exists. 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

% dict exists $names 3
1

How it works…

The dict exists command returns a Boolean value to indicate if the specified key exists in the dictionary referenced in name. A return ...

Get Tcl/Tk 8.5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.