| |
1.dict update
dict update diction key value
下面对调两个变量的值,v1,v2为指定的键值对应的值的别名,前面无$
% set ex {fn ann sn huan title miss}
fn ann sn huan title miss
% dict update ex fn v1 sn v2 {
> lassign [list $v1 $v2] v2 v1
> }
% puts $ex
fn huan sn ann title miss
%set pf {c 1 x 2 y 3}
proc sv {dictvar key} {
> upvar 1 $dictvar d
> dict update d $key v {
> set v [expr {$v**2}]
> }
> }
% sv pf y
9
dict update有个重要特点,更新只发生在dict update命令块结束的时候,未被子命令映射的关键字-关联值是不会受到影响的。
% dict update ex sn s notes n initial i {
> dict set ex title mrs
> unset s
> set n "have initial = [info exists i]"
> puts $ex
> }
fn huan sn ann title mrs
% puts $ex
fn huan title mrs notes {have initial = 0}
%
2.嵌套字典,支持的有dict get ,dict exists,dict set,dict unset,dict with
dict get $dict key1 key2
% set nestdic {fn ann sn huan}
fn ann sn huan
% dict set nestdic address street {ordinary way}
fn ann sn huan address {street {ordinary way}}
% dict set nestdic address city springfiels
fn ann sn huan address {street {ordinary way} city springfiels}
% dict unset nestdic address street
fn ann sn huan address {city springfiels}
dict exists $dict key1 key2
dict with与dict update相似,它容许吧一个字典打开到变量,但也有一个不同之处,dict with并没有让你控制那些关键字要处理,也没有让您裤子他们绑定到那些值,dict with吧指定的字典或子字典完全打开
% set ex {
> a {
> alph {a alp b bravo c charlie}
> animals {cow calf sheep lamb pig ? goose ? }
> }
> c {
> comedians {laurel&hardy morecambe&wise}
> }
> }
a {
alph {a alp b bravo c charlie}
animals {cow calf sheep lamb pig ? goose ? }
}
c {
comedians {laurel&hardy morecambe&wise}
}
% dict with ex c {
> puts "comedian:$comedians"
> lappend comedians "steven martin"
> }
comedian:laurel&hardy morecambe&wise {steven martin}
laurel&hardy morecambe&wise {steven martin} {steven martin}
% dict with ex a alph {
> puts "NATO ABC : $a $b $c"
> }
NATO ABC : alp bravo charlie
% dict with ex a animals {
> set pig piglet'
> set goose gosling
> }
gosling
% puts $ex
a {alph {a alp b bravo c charlie} animals {cow calf sheep lamb pig piglet' goose gosling}} c {comedians {laurel&hardy morecambe&wise {steven martin} {steven martin}}}
% dict with ex a {
> dict for {k v} $animals {
> puts "$k has baby $v"\}
> }
> }
extra characters after close-quote
% dict with ex a {
> dict for {k v } $animals {
> puts "$k:$v"
> }
> }
cow:calf
sheep:lamb
pig:piglet'
goose:gosling
%