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

Tcl: How to get value from nested dictionary by list of keys

我在使用键列表访问嵌套字典中的值时遇到困难。

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 不接受 list 作为参数。

dict get $testDict {*}$keyLst

参考文献:dict ; argument expansion