Tcl基礎學習(5):dict(字典)


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"
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM