Tcl collections - lists, dicts and array
Archive - Originally posted on "The Horse's Mouth" - 2012-01-16 17:18:52 - Graham EllisIn Tcl, almost all variables are what is described as "pure" - which means that they hold data as strings of text which can be passed, substituted with a $ prefix, etc. Special interpretation on pure variables allows them to be treated as:
• integers
• floats
• lists
• dicts
• file handles
Arrays, on the other hand, are NOT pure variables - they are special cases and this means they cannot be substituted with a $, nor passed into procs by value, nor passed back via return (you have to use upvar to get them in and out of a proc)
List example:
set demo {Anne Bill Charlotte Dennis Enid Fred Gwynn Henry Isobel}
set fourth [lindex $demo 3]
puts $fourth
Dict example:
set demo {Anne Jones Bill Brown Charlotte Steeple Dennis {The Menace} Enid Blyton
Fred Dibnah Gwynn Grimm Henry Eighth Isobel Quietly}
set surname [dict get $demo Enid]
puts $surname
With both lists and dicts, you can easily use single word values (and keys in the case of dicts) but need to apply protection if you want embedded special characters - and for this purpose the space is a special character.
lists are handled with a whole series of commands such as lsort, lindex and lappend, whereas with dictionaries all the actions are handled with the single dict command via a series of sub-commands.
The example code above may be seen in a complete but short sample program [here].
arrays are handles through the array command, and its sub-commands, and also with the use of round brackets to address individual members, which are pure strings. There's an example from our training notes [here] and another [here].
dicts were introduced into Tcl at version 8.5 ... and that's now been around long enough for it to be pretty unusual for us to come across 8.4 or earlier.
Advantages of dicts
- can use just like other pure variables
- ability to have dicts of dicts, lists of dicts, dicts of lists, etc
Advantages of arrays
- likely to be more efficient for larger volumes of data
- no need to worry if you've got Tcl 8.5 or not
See our Tcl courses if you want to come along and learn Tcl with us!