在使用dict exists
命令时,我厌倦了使用dict get
来防止运行时错误,因此我将dict get
包裹在一个" safe"本身的版本。但是,我无法弄清楚它为什么不起作用。 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}]
答案 0 :(得分:2)
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
您仍然需要展开{{1}},但至少对我而言,使用看起来像标准$args
调用的调用似乎是个好主意。