如何处理嵌套的dicts?

时间:2013-12-05 11:51:29

标签: tcl

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

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”命令中我想要提取等级值 - 我无法让它工作。 如果我在dict之外,我可以使用

set tmp [dict get $Courses 044262 grade] 

但在dict里面,我无法让它工作......尝试了许多$ key或$ val的组合,有或没有$符号

我做错了什么(如果有人可以推荐一本好书/网上tuturial有问题进行培训会很棒!)

1 个答案:

答案 0 :(得分:2)

使用您的特定字典,每个循环遍历$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这样的嵌入式数据库来管理数据......

相关问题