如何在tcl中使用dict append nested dict

How to use dict append nested dict in tcl

我想在 Tcl 中有一个嵌套字典,并附加一个值。 但是嵌套并没有真正起作用...... 见代码:

> set k [dict create]
> dict append k fee foo " kak"
> dict append k fee foo " poached"
> puts [dict get  [dict get $k fee] foo ]<code>

结果是:

missing value to go with key
    while executing
"dict get  [dict get $k fee] foo "
    invoked from within
"puts [dict get  [dict get $k fee] foo ]"

有什么想法吗?

您似乎没有正确创建字典:

% set k [dict create]
% dict append k fee {foo " kak"}
fee {foo " kak"}
% dict append k fee {foo " poached"}
fee {foo " kak"foo " poached"}

在这里你可以看到这可能不是你要找的。如果您允许我引用部分文档:

dict append dictionaryVariable key ?string ...?

This appends the given string (or strings) to the value that the given key maps to in the dictionary value contained in the given variable, writing the resulting dictionary value back to that variable. [...]

要创建一个具有多个深度的 dict,我会使用类似的方法,如果我必须尽可能遵循您的方法:

% set k [dict create]
% dict append k fee {foo kak}
fee {foo kak}
% dict set k fee foo "[dict get $k fee foo] poached"
fee {foo {kak poached}}

如果要将 poached 附加到字符串 kak 的值,则需要使用 dict set,它允许您修改任何深度的字典中的值,这是dict append的缺点。现在 dict get $k fee foo(与 [dict get [dict get $k fee] foo] 的作用相同)将为您提供 kak poached.

不过,我可能会将字典创建为:

set k [dict create foo {fee {kak poached}}]

这是另一种方法:

set k [dict create fee {foo {}}]
dict with k fee {append foo " kak"}
dict with k fee {append foo " poached"}
puts [dict get $k fee foo]

dict with 命令允许您为字典成员使用变量别名(只要它们已经存在,因此在第一行进行初始化)。可以在脚本之前给出一个或多个键,以找到您希望发生更改的字典级别。更改变量 foo 的值现在将更改 k.

中键 fee foo 的值

当然你也可以这样做:

set k [dict create fee {foo {}}]
dict with k fee {
    append foo " kak"
    append foo " poached"
}
puts [dict get $k fee foo]

文档:append, dict, puts, set