Debian Codegraph @

doc/dict.n

raw
1 '\"
2 '\" Copyright (c) 2003 Donal K. Fellows
3 '\"
4 '\" See the file "license.terms" for information on usage and redistribution
5 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
6 '\"
7 .TH dict n 8.5 Tcl "Tcl Built-In Commands"
8 .so man.macros
9 .BS
10 '\" Note: do not modify the .SH NAME line immediately below!
11 .SH NAME
12 dict \- Manipulate dictionaries
13 .SH SYNOPSIS
14 \fBdict \fIoption arg \fR?\fIarg ...\fR?
15 .BE
16 .SH DESCRIPTION
17 .PP
18 Performs one of several operations on dictionary values or variables
19 containing dictionary values (see the \fBDICTIONARY VALUES\fR section
20 below for a description), depending on \fIoption\fR. The legal
21 \fIoption\fRs (which may be abbreviated) are:
22 .TP
23 \fBdict append \fIdictionaryVariable key \fR?\fIstring ...\fR?
24 .
25 This appends the given string (or strings) to the value that the given
26 key maps to in the dictionary value contained in the given variable,
27 writing the resulting dictionary value back to that variable.
28 Non-existent keys are treated as if they map to an empty string. The
29 updated dictionary value is returned.
30 .TP
31 \fBdict create \fR?\fIkey value ...\fR?
32 .
33 Return a new dictionary that contains each of the key/value mappings
34 listed as arguments (keys and values alternating, with each key being
35 followed by its associated value.)
36 .TP
37 \fBdict exists \fIdictionaryValue key \fR?\fIkey ...\fR?
38 .
39 This returns a boolean value indicating whether the given key (or path
40 of keys through a set of nested dictionaries) exists in the given
41 dictionary value. This returns a true value exactly when \fBdict
42 get\fR on that path will succeed.
43 .TP
44 \fBdict filter \fIdictionaryValue filterType arg \fR?\fIarg ...\fR?
45 .
46 This takes a dictionary value and returns a new dictionary that
47 contains just those key/value pairs that match the specified filter
48 type (which may be abbreviated.) Supported filter types are:
49 .RS
50 .TP
51 \fBdict filter \fIdictionaryValue \fBkey\fR ?\fIglobPattern ...\fR?
52 .VS 8.6
53 The key rule only matches those key/value pairs whose keys match any
54 of the given patterns (in the style of \fBstring match\fR.)
55 .VE 8.6
56 .TP
57 \fBdict filter \fIdictionaryValue \fBscript {\fIkeyVariable valueVariable\fB} \fIscript\fR
58 .
59 The script rule tests for matching by assigning the key to the
60 \fIkeyVariable\fR and the value to the \fIvalueVariable\fR, and then evaluating
61 the given script which should result in a boolean value (with the
62 key/value pair only being included in the result of the \fBdict
63 filter\fR when a true value is returned.) Note that the first
64 argument after the rule selection word is a two-element list. If the
65 \fIscript\fR returns with a condition of \fBTCL_BREAK\fR, no further
66 key/value pairs are considered for inclusion in the resulting
67 dictionary, and a condition of \fBTCL_CONTINUE\fR is equivalent to a false
68 result. The key/value pairs are tested in the order in which the keys
69 were inserted into the dictionary.
70 .TP
71 \fBdict filter \fIdictionaryValue \fBvalue \fR?\fIglobPattern ...\fR?
72 .VS 8.6
73 The value rule only matches those key/value pairs whose values match any
74 of the given patterns (in the style of \fBstring match\fR.)
75 .VE 8.6
76 .RE
77 .TP
78 \fBdict for {\fIkeyVariable valueVariable\fB} \fIdictionaryValue body\fR
79 .
80 This command takes three arguments, the first a two-element list of
81 variable names (for the key and value respectively of each mapping in
82 the dictionary), the second the dictionary value to iterate across,
83 and the third a script to be evaluated for each mapping with the key
84 and value variables set appropriately (in the manner of \fBforeach\fR.)
85 The result of the command is an empty string. If any evaluation of the
86 body generates a \fBTCL_BREAK\fR result, no further pairs from the
87 dictionary will be iterated over and the \fBdict for\fR command will
88 terminate successfully immediately. If any evaluation of the body
89 generates a \fBTCL_CONTINUE\fR result, this shall be treated exactly like a
90 normal \fBTCL_OK\fR result. The order of iteration is the order in
91 which the keys were inserted into the dictionary.
92 .TP
93 \fBdict get \fIdictionaryValue \fR?\fIkey ...\fR?
94 .
95 Given a dictionary value (first argument) and a key (second argument),
96 this will retrieve the value for that key. Where several keys are
97 supplied, the behaviour of the command shall be as if the result of
98 \fBdict get $dictVal $key\fR was passed as the first argument to
99 \fBdict get\fR with the remaining arguments as second (and possibly
100 subsequent) arguments. This facilitates lookups in nested
101 dictionaries. For example, the following two commands are equivalent:
102 .RS
103 .PP
104 .CS
105 dict get $dict foo bar spong
106 dict get [dict get [dict get $dict foo] bar] spong
107 .CE
108 .PP
109 If no keys are provided, \fBdict get\fR will return a list containing pairs of
110 elements in a manner similar to \fBarray get\fR. That is, the first
111 element of each pair would be the key and the second element would be
112 the value for that key.
113 .PP
114 It is an error to attempt to retrieve a value for a key that is not
115 present in the dictionary.
116 .RE
117 .TP
118 \fBdict incr \fIdictionaryVariable key \fR?\fIincrement\fR?
119 .
120 This adds the given increment value (an integer that defaults to 1 if
121 not specified) to the value that the given key maps to in the
122 dictionary value contained in the given variable, writing the
123 resulting dictionary value back to that variable. Non-existent keys
124 are treated as if they map to 0. It is an error to increment a value
125 for an existing key if that value is not an integer. The updated
126 dictionary value is returned.
127 .TP
128 \fBdict info \fIdictionaryValue\fR
129 .
130 This returns information (intended for display to people) about the
131 given dictionary though the format of this data is dependent on the
132 implementation of the dictionary. For dictionaries that are
133 implemented by hash tables, it is expected that this will return the
134 string produced by \fBTcl_HashStats\fR, similar to \fBarray statistics\fR.
135 .TP
136 \fBdict keys \fIdictionaryValue \fR?\fIglobPattern\fR?
137 .
138 Return a list of all keys in the given dictionary value. If a pattern
139 is supplied, only those keys that match it (according to the rules of
140 \fBstring match\fR) will be returned. The returned keys will be in the
141 order that they were inserted into the dictionary.
142 .TP
143 \fBdict lappend \fIdictionaryVariable key \fR?\fIvalue ...\fR?
144 .
145 This appends the given items to the list value that the given key maps
146 to in the dictionary value contained in the given variable, writing
147 the resulting dictionary value back to that variable. Non-existent
148 keys are treated as if they map to an empty list, and it is legal for
149 there to be no items to append to the list. It is an error for the
150 value that the key maps to to not be representable as a list. The
151 updated dictionary value is returned.
152 .TP
153 \fBdict map \fR{\fIkeyVariable valueVariable\fR} \fIdictionaryValue body\fR
154 .
155 This command applies a transformation to each element of a dictionary,
156 returning a new dictionary. It takes three arguments: the first is a
157 two-element list of variable names (for the key and value respectively of each
158 mapping in the dictionary), the second the dictionary value to iterate across,
159 and the third a script to be evaluated for each mapping with the key and value
160 variables set appropriately (in the manner of \fBlmap\fR). In an iteration
161 where the evaluated script completes normally (\fBTCL_OK\fR, as opposed to an
162 \fBerror\fR, etc.) the result of the script is put into an accumulator
163 dictionary using the key that is the current contents of the \fIkeyVariable\fR
164 variable at that point. The result of the \fBdict map\fR command is the
165 accumulator dictionary after all keys have been iterated over.
166 .RS
167 .PP
168 If the evaluation of the body for any particular step generates a \fBbreak\fR,
169 no further pairs from the dictionary will be iterated over and the \fBdict
170 map\fR command will terminate successfully immediately. If the evaluation of
171 the body for a particular step generates a \fBcontinue\fR result, the current
172 iteration is aborted and the accumulator dictionary is not modified. The order
173 of iteration is the natural order of the dictionary (typically the order in
174 which the keys were added to the dictionary; the order is the same as that
175 used in \fBdict for\fR).
176 .RE
177 .TP
178 \fBdict merge \fR?\fIdictionaryValue ...\fR?
179 .
180 Return a dictionary that contains the contents of each of the
181 \fIdictionaryValue\fR arguments. Where two (or more) dictionaries
182 contain a mapping for the same key, the resulting dictionary maps that
183 key to the value according to the last dictionary on the command line
184 containing a mapping for that key.
185 .TP
186 \fBdict remove \fIdictionaryValue \fR?\fIkey ...\fR?
187 .
188 Return a new dictionary that is a copy of an old one passed in as
189 first argument except without mappings for each of the keys listed.
190 It is legal for there to be no keys to remove, and it also legal for
191 any of the keys to be removed to not be present in the input
192 dictionary in the first place.
193 .TP
194 \fBdict replace \fIdictionaryValue \fR?\fIkey value ...\fR?
195 .
196 Return a new dictionary that is a copy of an old one passed in as
197 first argument except with some values different or some extra
198 key/value pairs added. It is legal for this command to be called with
199 no key/value pairs, but illegal for this command to be called with a
200 key but no value.
201 .TP
202 \fBdict set \fIdictionaryVariable key \fR?\fIkey ...\fR? \fIvalue\fR
203 .
204 This operation takes the name of a variable containing a dictionary
205 value and places an updated dictionary value in that variable
206 containing a mapping from the given key to the given value. When
207 multiple keys are present, this operation creates or updates a chain
208 of nested dictionaries. The updated dictionary value is returned.
209 .TP
210 \fBdict size \fIdictionaryValue\fR
211 .
212 Return the number of key/value mappings in the given dictionary value.
213 .TP
214 \fBdict unset \fIdictionaryVariable key \fR?\fIkey ...\fR?
215 .
216 This operation (the companion to \fBdict set\fR) takes the name of a
217 variable containing a dictionary value and places an updated
218 dictionary value in that variable that does not contain a mapping for
219 the given key. Where multiple keys are present, this describes a path
220 through nested dictionaries to the mapping to remove. At least one key
221 must be specified, but the last key on the key-path need not exist.
222 All other components on the path must exist. The updated dictionary
223 value is returned.
224 .TP
225 \fBdict update \fIdictionaryVariable key varName \fR?\fIkey varName ...\fR? \fIbody\fR
226 .
227 Execute the Tcl script in \fIbody\fR with the value for each \fIkey\fR
228 (as found by reading the dictionary value in \fIdictionaryVariable\fR)
229 mapped to the variable \fIvarName\fR. There may be multiple
230 \fIkey\fR/\fIvarName\fR pairs. If a \fIkey\fR does not have a mapping,
231 that corresponds to an unset \fIvarName\fR. When \fIbody\fR
232 terminates, any changes made to the \fIvarName\fRs is reflected back
233 to the dictionary within \fIdictionaryVariable\fR (unless
234 \fIdictionaryVariable\fR itself becomes unreadable, when all updates
235 are silently discarded), even if the result of \fIbody\fR is an error
236 or some other kind of exceptional exit. The result of \fBdict
237 update\fR is (unless some kind of error occurs) the result of the
238 evaluation of \fIbody\fR.
239 .RS
240 .PP
241 Each \fIvarName\fR is mapped in the scope enclosing the \fBdict update\fR;
242 it is recommended that this command only be used in a local scope
243 (\fBproc\fRedure, lambda term for \fBapply\fR, or method). Because of
244 this, the variables set by \fBdict update\fR will continue to
245 exist after the command finishes (unless explicitly \fBunset\fR).
246 Note that the mapping of values to variables
247 does not use traces; changes to the \fIdictionaryVariable\fR's
248 contents only happen when \fIbody\fR terminates.
249 .RE
250 .TP
251 \fBdict values \fIdictionaryValue \fR?\fIglobPattern\fR?
252 .
253 Return a list of all values in the given dictionary value. If a
254 pattern is supplied, only those values that match it (according to the
255 rules of \fBstring match\fR) will be returned. The returned values
256 will be in the order of that the keys associated with those values
257 were inserted into the dictionary.
258 .TP
259 \fBdict with \fIdictionaryVariable \fR?\fIkey ...\fR? \fIbody\fR
260 .
261 Execute the Tcl script in \fIbody\fR with the value for each key in
262 \fIdictionaryVariable\fR mapped (in a manner similarly to \fBdict
263 update\fR) to a variable with the same name. Where one or more
264 \fIkey\fRs are available, these indicate a chain of nested
265 dictionaries, with the innermost dictionary being the one opened out
266 for the execution of \fIbody\fR. As with \fBdict update\fR, making
267 \fIdictionaryVariable\fR unreadable will make the updates to the
268 dictionary be discarded, and this also happens if the contents of
269 \fIdictionaryVariable\fR are adjusted so that the chain of
270 dictionaries no longer exists. The result of \fBdict with\fR is
271 (unless some kind of error occurs) the result of the evaluation of
272 \fIbody\fR.
273 .RS
274 .PP
275 The variables are mapped in the scope enclosing the \fBdict with\fR;
276 it is recommended that this command only be used in a local scope
277 (\fBproc\fRedure, lambda term for \fBapply\fR, or method). Because of
278 this, the variables set by \fBdict with\fR will continue to
279 exist after the command finishes (unless explicitly \fBunset\fR).
280 Note that the mapping of values to variables does not use
281 traces; changes to the \fIdictionaryVariable\fR's contents only happen
282 when \fIbody\fR terminates.
283 .PP
284 If the \fIdictionaryVariable\fR contains a value that is not a dictionary at
285 the point when the \fIbody\fR terminates (which can easily happen if the name
286 is the same as any of the keys in dictionary) then an error occurs at that
287 point. This command is thus not recommended for use when the keys in the
288 dictionary are expected to clash with the \fIdictionaryVariable\fR name
289 itself. Where the contained key does map to a dictionary, the net effect is to
290 combine that inner dictionary into the outer dictionary; see the
291 \fBEXAMPLES\fR below for an illustration of this.
292 .RE
293 .SH "DICTIONARY VALUES"
294 .PP
295 Dictionaries are values that contain an efficient, order-preserving
296 mapping from arbitrary keys to arbitrary values.
297 Each key in the dictionary maps to a single value.
298 They have a textual format that is exactly that of any list with an
299 even number of elements, with each mapping in the dictionary being
300 represented as two items in the list. When a command takes a
301 dictionary and produces a new dictionary based on it (either returning
302 it or writing it back into the variable that the starting dictionary
303 was read from) the new dictionary will have the same order of keys,
304 modulo any deleted keys and with new keys added on to the end.
305 When a string is interpreted as a dictionary and it would otherwise
306 have duplicate keys, only the last value for a particular key is used;
307 the others are ignored, meaning that,
308 .QW "apple banana"
309 and
310 .QW "apple carrot apple banana"
311 are equivalent dictionaries (with different string representations).
312 .PP
313 Operations that derive a new dictionary from an old one (e.g., updates
314 like \fBdict set\fR and \fBdict unset\fR) preserve the order of keys
315 in the dictionary. The exceptions to this are for any new keys they
316 add, which are appended to the sequence, and any keys that are
317 removed, which are excised from the order.
318 .SH EXAMPLES
319 .PP
320 Basic dictionary usage:
321 .PP
322 .CS
323 # Make a dictionary to map extensions to descriptions
324 set filetypes [\fBdict create\fR .txt "Text File" .tcl "Tcl File"]
325
326 # Add/update the dictionary
327 \fBdict set\fR filetypes .tcl "Tcl Script"
328 \fBdict set\fR filetypes .tm "Tcl Module"
329 \fBdict set\fR filetypes .gif "GIF Image"
330 \fBdict set\fR filetypes .png "PNG Image"
331
332 # Simple read from the dictionary
333 set ext ".tcl"
334 set desc [\fBdict get\fR $filetypes $ext]
335 puts "$ext is for a $desc"
336
337 # Somewhat more complex, with existence test
338 foreach filename [glob *] {
339 set ext [file extension $filename]
340 if {[\fBdict exists\fR $filetypes $ext]} {
341 puts "$filename is a [\fBdict get\fR $filetypes $ext]"
342 }
343 }
344 .CE
345 .PP
346 Constructing and using nested dictionaries:
347 .PP
348 .CS
349 # Data for one employee
350 \fBdict set\fR employeeInfo 12345-A forenames "Joe"
351 \fBdict set\fR employeeInfo 12345-A surname "Schmoe"
352 \fBdict set\fR employeeInfo 12345-A street "147 Short Street"
353 \fBdict set\fR employeeInfo 12345-A city "Springfield"
354 \fBdict set\fR employeeInfo 12345-A phone "555-1234"
355 # Data for another employee
356 \fBdict set\fR employeeInfo 98372-J forenames "Anne"
357 \fBdict set\fR employeeInfo 98372-J surname "Other"
358 \fBdict set\fR employeeInfo 98372-J street "32995 Oakdale Way"
359 \fBdict set\fR employeeInfo 98372-J city "Springfield"
360 \fBdict set\fR employeeInfo 98372-J phone "555-8765"
361 # The above data probably ought to come from a database...
362
363 # Print out some employee info
364 set i 0
365 puts "There are [\fBdict size\fR $employeeInfo] employees"
366 \fBdict for\fR {id info} $employeeInfo {
367 puts "Employee #[incr i]: $id"
368 \fBdict with\fR info {
369 puts " Name: $forenames $surname"
370 puts " Address: $street, $city"
371 puts " Telephone: $phone"
372 }
373 }
374 # Another way to iterate and pick out names...
375 foreach id [\fBdict keys\fR $employeeInfo] {
376 puts "Hello, [\fBdict get\fR $employeeInfo $id forenames]!"
377 }
378 .CE
379 .PP
380 A localizable version of \fBstring toupper\fR:
381 .PP
382 .CS
383 # Set up the basic C locale
384 set capital [\fBdict create\fR C [\fBdict create\fR]]
385 foreach c [split {abcdefghijklmnopqrstuvwxyz} ""] {
386 \fBdict set\fR capital C $c [string toupper $c]
387 }
388
389 # English locales can luckily share the "C" locale
390 \fBdict set\fR capital en [\fBdict get\fR $capital C]
391 \fBdict set\fR capital en_US [\fBdict get\fR $capital C]
392 \fBdict set\fR capital en_GB [\fBdict get\fR $capital C]
393
394 # ... and so on for other supported languages ...
395
396 # Now get the mapping for the current locale and use it.
397 set upperCaseMap [\fBdict get\fR $capital $env(LANG)]
398 set upperCase [string map $upperCaseMap $string]
399 .CE
400 .PP
401 Showing the detail of \fBdict with\fR:
402 .PP
403 .CS
404 proc sumDictionary {varName} {
405 upvar 1 $varName vbl
406 foreach key [\fBdict keys\fR $vbl] {
407 # Manufacture an entry in the subdictionary
408 \fBdict set\fR vbl $key total 0
409 # Add the values and remove the old
410 \fBdict with\fR vbl $key {
411 set total [expr {$x + $y + $z}]
412 unset x y z
413 }
414 }
415 puts "last total was $total, for key $key"
416 }
417
418 set myDict {
419 a {x 1 y 2 z 3}
420 b {x 6 y 5 z 4}
421 }
422
423 sumDictionary myDict
424 # prints: \fIlast total was 15, for key b\fR
425
426 puts "dictionary is now \\"$myDict\\""
427 # prints: \fIdictionary is now "a {total 6} b {total 15}"\fR
428 .CE
429 .PP
430 When \fBdict with\fR is used with a key that clashes with the name of the
431 dictionary variable:
432 .PP
433 .CS
434 set foo {foo {a b} bar 2 baz 3}
435 \fBdict with\fR foo {}
436 puts $foo
437 # prints: \fIa b foo {a b} bar 2 baz 3\fR
438 .CE
439 .SH "SEE ALSO"
440 append(n), array(n), foreach(n), incr(n), list(n), lappend(n), lmap(n), set(n)
441 .SH KEYWORDS
442 dictionary, create, update, lookup, iterate, filter, map
443 '\" Local Variables:
444 '\" mode: nroff
445 '\" End: