【问题标题】:How to handle nested dicts?如何处理嵌套的字典?
【发布时间】:2013-12-05 22:15:28
【问题描述】:

我有点困惑。我已经建立了一个字典 - 和一个嵌套字典 这是它的“布局”

dict for {key val} $Courses {
puts " the key = $key "
puts " the val = $val "
                        }

。 . .

 the key = 044262
 the val = name tehen grade 91
 the key = 044148
 the val = name galim grade tbd2

在“dict for”命令中,我想提取等级值 - 我无法让它工作。 如果我在字典之外,我可以使用

set tmp [dict get $Courses 044262 grade] 

但是在 dict 里面我不能让它工作...尝试了许多 $key 或 $val 的组合,带或不带 $ 符号

我做错了什么(如果有人可以推荐一本有问题的好书/在线教程,那就太好了!)

【问题讨论】:

    标签: tcl


    【解决方案1】:

    对于您的特定字典,循环中的每次运行都有$val 是它自己的字典。然后,您可以使用普通的字典操作进行访问;例如:

    dict for {key val} $Courses {
        puts " the key = $key "
        puts " the val = $val "
        # Iterate over contents
        dict for {k v} $val {
            puts "$k => $v"
        }
        # Picking out a particular key
        puts "The grade was [dict get $val grade]" 
    }
    

    请注意,如果您正在更新,更新不会写回Courses;字典是写时复制的值,这对 Tcl 来说是正常的。您必须进行这样的更新:

    dict set Courses $key grade "Excellent, dudes!"
    

    还要注意,迭代不会看到更改(您在启动dict for 时获取了一个逻辑副本)。如果你真的想看到变化,你需要完全不同地编写循环:

    foreach key [dict keys $Courses] {
        puts " the key = $key "
        puts " the val = [dict get $Courses $key] "
        dict for {k v} [dict get $Courses $key] {
            puts "$k => $v"
        }
        puts "The grade was [dict get $Courses $key grade]"
        dict set Courses $key grade 1234567890
        puts "The grade is changed to [dict get $Courses $key grade]"
    }
    

    如果事情变得比这复杂得多,我会认真考虑使用像 SQLite 这样的嵌入式数据库来管理数据……

    【讨论】:

    • tnx 兄弟。很大的帮助
    猜你喜欢
    • 2010-11-19
    • 2021-12-19
    • 2020-12-03
    • 2020-10-21
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    相关资源
    最近更新 更多