tcl数组是变量的集合,而不是一个数值,不能做为一个值直接传递到进程中,且不能包含在其他数据结构中。只能通过array get和array set将数组转换并返回才能这样使用。而dict字典就是为了弥补这些不足,不像数组中的集合和列表的有序序列,字典是键到值的映射,字典中全部是值,既可以直接传递给一个过程,还能够对字典进行嵌套,让字典中的某一个值包含另一个字典。
创建一个字典:
- dict set dictname key value
- dict create dictname key1 value1 key2 value2....keyn valuen
获取字典的大小:
- dict size $dictname
检索字典的所有键:返回所有键
- dict keys $dictname
检索字典的所有值:返回所有值
- dict values $dictname
对字典键的值进行索引:返回值
- dict get $dictname keysname
检查键是否存在字典中:返回1(存在)和0(不存在)
- dict exists $dictname keysname
#方式1:创建字典colours
dict set colours colour1 red
puts $colours
dict set colours colour2 green
puts $colours
#方式2:创建字典colours
set colours [dict create colour1 "black" colour2 "white"]
puts $colours
#获取字典大小
puts "The size of the dictionary is:[dict size $colours]"
#对字典中的所有键进行索引
set keys [dict keys $colours]
puts "All keys in the dictionary is :$keys"
#对字典中的所有值进行索引
set values [dict values $colours]
puts "All values of the dictionary is :$values"
#对字典键的值进行检索
set value [dict get $colours colour1]
puts "The value of the colour1 in the dictionary is :$value"
#检查键是否存在于字典中
set result [dict exists $colours colour1]
puts $result
>> colour1 red
colour1 red colour2 green
colour1 black colour2 white
The size of the dictionary is:2
All keys in the dictionary is :colour1 colour2
All values of the dictionary is :black white
The value of the colour1 in the dictionary is :black
1
字典的循环遍历和嵌套
字典的嵌套
- dict set dictname key1 key2 value
字典的循环遍历:foreach的特殊版本
- dict for {id info} $dictnames
dict set clients 1 forenames Joe
dict set clients 1 surname Schmoe
dict set clients 2 forenames Anne
dict set clients 2 surname Other
puts "Number of clients: [dict size $clients]"
dict for {id info} $clients {
puts "Client $id:"
dict with info {
puts "Name: $forenames $surname"
}
}