How do I create and iterate through a hash of hashes in TCL?
If I have data like:
foo = {
a => {
aa => { aa1 aa2 aa3 }
ab => { ab1 ab2 ab3 }
ac => { ac1 ac2 ac3 }
}
b => {
ba => { ba1 ba2 ba3 }
bb => { bb1 bb2 bb3 }
bc => { bc1 bc2 bc3 }
}
c => {
ca => { ca1 ca2 ca3 }
cb => { cb1 cb2 cb3 }
cc => { cc1 cc2 cc3 }
}
}
How do I create such a hash by inserting one leaf-node data item at a time. Something like:
lappend foo(a)(ab) "ab1"
Then how do I iterate over all data elements? like:
foreach key in foo {
foreach sub_key in foo($key) {
foreach elem in foo($key)($sub_key) {
puts "foo\($key\)\($sub_key\) is $elem"
}
}
}
Edit : Unfortunately, I do not have access to the newer 'dict' construct.
If you're not using Tcl 8.5, then you can use arrays. Note that arrays are one-dimensional, but the key is an arbitrary string that can be used to fake multi-dimensionality:
array set foo {}
foreach first {a b c} {
foreach second {a b c} {
foreach third {1 2 3} {
lappend foo($first,$first$second) "$first$second$third"
}
}
}
parray data
and output it -- note: array keys, unlike dictionary keys, are unordered:
foreach key [array names foo] {
foreach elem $foo($key) {
puts "$key\t$elem"
}
}
If you are given the keys (example 'b' and 'bc') you can get the value thusly:
set key1 b
set key2 bc
foreach elem $foo($key1,$key2) {puts $elem}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With