user3629892
user3629892

Reputation: 3046

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

I'd like to add multiple key-value pairs to a dict.

I tried append, lappend and set but the key-value pairs get appended as one big string.

Here's the code:

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

]

How do I do this?

Upvotes: 0

Views: 1972

Answers (2)

Johannes Kuhn
Johannes Kuhn

Reputation: 15173

I think you want something like 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

Upvotes: 1

patthoyts
patthoyts

Reputation: 33203

It doesn't provide that natively. However, the dict command is implemented as an ensemble and can be extended. Some examples are on the dicttools wiki page but in this case the following defines a suitable procedure then adds it to the dict ensemble so that you can call it as a single command.

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]

Example use:

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

Upvotes: 4

Related Questions