tcl Iterating over a dictionary


You can iterate over the contents of a dictionary with dict for, which is similar to foreach:

set theDict {abcd {ab cd} bcde {ef gh} cdef {ij kl}}
dict for {theKey theValue} $theDict {
    puts "$theKey -> $theValue"

This produces this output:

abcd -> ab cd
bcde -> ef gh
cdef -> ij kl

You'd get the same output by using dict keys to list the keys and iterating over that:

foreach theKey [dict keys $theDict] {
    set theValue [dict get $theDict $theKey]
    puts "$theKey -> $theValue"

But dict for is more efficient.