Tcl:如何通过键列表从嵌套字典中获取值(Tcl: How to get value from nested dictionary by list of keys)

编程入门 行业动态 更新时间:2024-10-25 12:18:49
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在这种情况下起作用 - 必须有更好的方法直接执行此操作。

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

I have difficulty accessing values in nested dictionary by using 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

While eval works in this instance - There must be better way to do this directly.

Any idea how to access nested dictionary values by key list in variable?

最满意答案

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

dict get $testDict {*}$keyLst

参考文献: dict ; 论证扩展

You need to expand the list (or string) into separate words. dict does not take a list as an argument.

dict get $testDict {*}$keyLst

References: dict ; argument expansion

更多推荐

本文发布于:2023-08-03 21:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1401121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字典   列表   Tcl   keys

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!