TCL:一次将几个键值对附加到字典

TCL: append several key-value pairs to dict at once

我想将多个键值对添加到 dict

我尝试了 append、lappend 和 set,但键值对被附加为一个大字符串。

代码如下:

set myNewDict [dict lappend $myOldDict \
"field one" "VALUE1" \
"field two" "VALUE2" \
"field three" "VALUE3" \
"field four" "VALUE4"

]

我该怎么做?

它本身不提供。但是,dict command is implemented as an ensemble and can be extended. Some examples are on the dicttools wiki 页面但在这种情况下,下面定义了一个合适的过程,然后将其添加到 dict 集合中,以便您可以将其作为单个命令调用。

proc ::tcl::dict::append2 {dictVarName args} {
    upvar 1 d $dictVarName
    foreach {k v} $args {
        dict append d $k $v
    }
}
namespace ensemble configure dict -map \
    [linsert [namespace ensemble configure dict -map] end \
    append2 ::tcl::dict::append2]

使用示例:

% set d [dict create]
% set d
% dict append2 d a 1 b 2 c 3
% set d
a 1 b 2 c 3

我想你想要这样的东西 dict merge:

% set d [dict create 1 foo 2 bar]
1 foo 2 bar
% set d [dict merge $d [dict create \
2 baz \
3 example \
4 stuff]]
1 foo 2 baz 3 example 4 stuff