A-A+

TCL中字典的创建和更新

2020年03月03日 脚本 阅读 1,279 views 次

在Tcl中使用命令 dict create创建字典。命令的格式为:

dict create ?key value ...?

它获取任意多个关键字关联值对,然后生成一个包含这些关键字关联值对的字典。字典中关键字的顺序是它们第一次出现的先后顺序,当一个关键字多次出现时,采用最后与它关联的值。使用 dict replace更新字典时也适用这条规则。例如:

dict create a b c {d e} {f g} h a "b repeated"

→a {b repeated} c {d e} {f g} h

dict replace用来更新字典中的值或添加关键字,格式为:

dict replace dictionaryValue ?key value ...?

例如:

set example [dict create firstname Ann initial E surname Huan]

→firstname Ann initial E surname Huan

dict replace $example initial Y

→firstname Ann initial Y surname Huan

dict replace $example title Mrs surname Boddie

→firstname Ann initial E surname Boddie title Mrs

如果希望删除一个字典中的某个关键字,使用dict remove命令,格式如下:

dict remove dictionaryValue ?key ...?

例如:

dict remove $example initial

→firstname Ann surname Huan

注意,试图删除一个不存在的关键字并不会导致错误。 dict merge命令通过融合两个或更多字典,创建一个新字典,源字典分别作为独立的参数提供。格式为:

dict merge ?dictionaryValue ...?

当两个或多个字典有同样的关键字时,生成的字典会把这个关键字映射到命令中最后出现该关键字的字典中的关联值。例如:

set colors1 {foreground white background black}

set colors2 {highlight red foreground green}

dict merge $colors1 $colors2

→foreground green background black highlight red

当有一个作为变量的字典时,可以通过添加关键字,改变关键字的映射或删除关键字来更新它。前两个操作由dict set命令完成,第三个操作由 dict unset命令完成。dict set命令获取要更新的变量名,要创建或更新的关键字以及关键字对应的关联值,并把更新后的字典写回原字典变量中。 dict unset命令也要获取同样的参数,只是不需要关联值。例如:

set example [ dict create firstname Ann initial E surname Huan title Miss]

→firstname Ann initial E surname Huan title Miss

dict set $example title Mrs

→firstname Ann initial E surname Huan title Mrs

dict get $example title

→Mrs

dict unset $example initial

→firstname Ann surname Boddie title Mrs

dict get Example initial

→key " initial " not known in dictionary

个人公众号“数字化设计CAX联盟”,欢迎关注,共同交流
标签:
为您推荐:

给我留言

© 坐倚北风 版权所有 严禁镜像复制 苏ICP备15034888号. 基于 Ality 主题定制 AliCMS
联系邮箱:leanwind@163.con,微信公众号:数字化设计CAX联盟

用户登录

分享到: