为 dict get 命令制作了一个 "safety" 包装器,但无法使其工作

Made a "safety" wrapper for dict get command, but can't make it work

我厌倦了使用 dict exists 来防止在使用 dict get 命令时出现 运行time 错误,所以我将 dict get 包装在 [=17= 中] 自己的版本。但是,我无法弄清楚为什么它不起作用。 dict exists 命令似乎不接受我参数化键的方式。我没想到 运行 做这么简单的事情会遇到任何问题,但我一定是犯了一个愚蠢的错误。这是代码:

#====================================================================================================
# dictGet
#
#   Desc:   Safe version of "dict get".  Checks to make sure a dict key exists before attempting to
#           retrieve it, avoiding run-time error if it does not.
#   Param:  dictName    -   The name of the dict to retrieve from.
#           keys        -   List of one or more dict keys terminating with the desired key from
#                           which the value is desired.
#   Return: The value of the dict key; -1 if the key does not exist.
#====================================================================================================
proc dictGet {theDict keys} {
    if {[dict exists $theDict [split $keys]]} {
        return [dict get $theDict [split $keys]]
    } else {
        return -1
    }
}

#====================================================================================================
#Test...
dict set myDict 0 firstName "Shao"
dict set myDict 0 lastName "Kahn"

puts [dictGet $myDict {0 firstName}]

split命令不会改变按键所在位置的字数。如果拆分列表 {0 firstName},结果仍然是列表 {0 firstName}。要获取单个密钥,请使用 {*}.

展开列表
set theDict {0 {firstName foo} 1 {firstName bar}}
# -> 0 {firstName foo} 1 {firstName bar}
set keys {0 firstName}
# -> 0 firstName
list dict exists $theDict [split $keys]
# -> dict exists {0 {firstName foo} 1 {firstName bar}} {0 firstName}
list dict exists $theDict {*}$keys
# -> dict exists {0 {firstName foo} 1 {firstName bar}} 0 firstName

另外,如果你使用这个:

proc dictGet {theDict args} {

您可以像这样调用命令:

dictGet $myDict 0 firstName

您仍然需要扩展 $args,但至少对我来说,使用看起来像标准 dict get 调用的调用似乎是个好主意。

文档:dict, list, proc, set, split, {*}