2016-02-17 72 views
1

我很难通过使用键列表来访问嵌套字典中的值。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 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在这种情况下工作 - 必须有更好的方式来直接做到这一点。

任何想法如何通过变量中的键列表访问嵌套字典值?

+0

如果它只是代码风格,那么你可以在[代码评论](http://codereview.stackexchange.com/)上提问。 –

回答

2

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

dict get $testDict {*}$keyLst 

参考文献:dict; argument expansion

+0

如果我们默认创建了关键列表,那么使用任意键将会变得非常烦人,并且(因此,因为懒惰)会容易出错。这是一个权衡。 –

+0

非常感谢Tcl参数扩展介绍 - 非常方便。 我明白Tcl设计中的权衡 - 很遗憾,B.Welsh Tcl书籍早于词典 - 我敢打赌,他会涵盖它。 :-) –

相关问题