Dictionary Tcl:如何通过键列表从嵌套字典中获取值

Dictionary Tcl:如何通过键列表从嵌套字典中获取值,dictionary,tcl,Dictionary,Tcl,我很难使用键列表访问嵌套字典中的值 dict set testDict library [dict create NY [dict create section [dict create adult [dict create book cinderella]]]] library {NY {section {adult {book cinderella}}}} # I can access the value by: dict get $testDict library NY section a

我很难使用键列表访问嵌套字典中的值

dict set testDict library [dict create NY [dict create section [dict create adult [dict create book cinderella]]]]
library {NY {section {adult {book cinderella}}}}
# I can access the value by:
dict get $testDict library NY section adult book
cinderella

# cannot access the same by list of keys in a variable
set keyLst {library NY section adult book}
library NY section adult book
set keyStr "library NY section adult book"
library NY section adult book

dict get $testDict $keyLst
key "library NY section adult book" not known in dictionary
dict get $testDict $keyStr
key "library NY section adults book" not known in dictionary

# The only not elegant solution I came up is using eval + list
eval dict get \$testDict $keyStr
key "adults" not known in dictionary

eval dict get \$testDict $keyLst
cinderella
虽然eval在这种情况下起作用,但必须有更好的方法直接实现这一点


知道如何通过变量中的键列表访问嵌套的字典值吗?

您需要将列表(或字符串)展开为单独的单词。
dict
不将
列表
作为参数

dict get $testDict {*}$keyLst

参考文献:

如果只是代码风格,那么你可以继续问。如果我们默认设置了键列表,使用任意键会变得非常烦人,并且(因此,因为懒惰)容易出错。这是一种折衷。非常感谢您对Tcl论点扩展的介绍-非常方便。我理解Tcl设计中的权衡——遗憾的是,B.威尔士Tcl的书比字典早——我敢打赌,他会涵盖它的。:-)