TCL更新字典中的值
1、dict append/lappend
要在字典的值中添加一个或一些字符串,最简单的方法是使用dict append命令,格式为:
dict append dictionaryVariable key ?string...?
它获取想要更新的字典变量名,想要更新其关联值的关键字,想要添加到值中的一个或多个字符串,返回更新后的字典,并把它写回原字典变量。
set example {firstname Ann surname Huantitle Miss}
dict append example firstname ie
→firstname Annie surname Huan title Miss
类似地,想要在字典值中创建列表时,可以使用 dict lappend子命令。例如:
set shopping {fruit apple veg carrot}
dict lappend shopping fruit orange
→fruit {apple orange} veg carrot
2、dict incr
dict令支持的另一个更新操作是dict incr。格式为:
dict incr dictionaryVariable key?increment?
它获取一个包含字典的变量,一个将要对其关联值进行增加操作的关键字,以及一个可选的值,用来设置增加量。命令的结果是更新后的字典,也会写回原字典变量中。与普通的incr命令相似,指定的关键字不必事先在字典中存在,如果不存在,就视为事先存在值为0的该关键字。例如,使用下面的过程统计一段文字中各单词出现的次数。
proc computeHistogram {text} {
set frequencies
foreach word [split $text] {
#Ignore empty words caused by double spaces
if {$word eq “ “} continue;
dict incr frequencies [string tolower$word]
}
return frequencies
}
computeHistogram "this day is a happy happyday”
→ this 1 day 2 is 1 a 1 happy 2
3、dict update
dict update命令的格式为:
dict update dictionaryVariable key varName?key varName ...? body
它获取包含一个字典的变量,字典中的关键字的一个列表,及与关键字关联的变量,以及由Tcl脚本描述的、要对这些变量进行的更新操作。这个脚本的结果也是整个dict update命令的结果。执行完脚本后,变量会被写回原来的字典变量中,从而允许对字典进行任意复杂的更新。
如果一个指定的关键字在开始dict update命令时的字典中不存在,那么在开始执行脚本块的时候该关键字的值为未设置。而在脚本的最后,没有关联值的关键字会从字典中移除。即如果关联值不存在,关键字也不存在。
使用这种机制可以进行各种各样的更新。例如,下面这个示例是对dict unset命令的复用。
dict update aDictionaryVariable $theKeylocalVar {
unset localVar
}
还可以进行更复杂的更新。下面是在两个关键字之间交换关联值的示例。
set example {firstname Ann surname Huantitle Miss}
dict update example firstname v1 surname v2{
lassign [list $v1 $v2] v2 v1
}
puts $example
→firstname Huansurname Ann title Miss
下面这个示例演示了如何对一个值求平方。
proc squareValue {dictVar key} {
upvar 1 $dictvar d
dict update d $key v{
set v [expr {$v **2}]
}
}
set polyFactors {C 1 x 2 y 3}
squareValue polyFactors y
→C 1 x 2 y 9
这里有一个重要特点,更新只发生在dictupdate命令块结束的时候,未被子命令映射的关键字关联值对是不会受到影响的。明白这个特点可以更容易地理解进行复杂的更新操作时系统的行为。例如:
set example {firstname Ann surname Huantitle Miss}
→firstname Annsurname Huan title Miss
set I "a dummy value"
dict update example surname s notes ninitial i {
dict set example title Mrs
unset s
set n "have initital =[info exists i] "
puts $example
}
→firstname Annsurname Huan title Mrs
puts $example
→firstname Anntitle Mrs notes {have initial=0}
尽管在dict update的脚本块中s变量被移除了,这个移除操作要在命令结束,更新后的字典写回变量时才会发生,并移除surname关键字。类似地,关键字initial开始时在字典中并不存在,所以变量i未设置。