- dict for {keyVar valueVar} dictionaryValue body
# Data for one employee
dict set employeeInfo 12345-A forenames "Joe"
dict set employeeInfo 12345-A surname "Schmoe"
dict set employeeInfo 12345-A street "147 Short Street"
dict set employeeInfo 12345-A city "Springfield"
dict set employeeInfo 12345-A phone "555-1234"
# Data for another employee
dict set employeeInfo 98372-J forenames "Anne"
dict set employeeInfo 98372-J surname "Other"
dict set employeeInfo 98372-J street "32995 Oakdale Way"
dict set employeeInfo 98372-J city "Springfield"
dict set employeeInfo 98372-J phone "555-8765"
# The above data probably ought to come from a database...
# Print out some employee info
set i 0
puts "There are [dict size $employeeInfo] employees"
dict for {id info} $employeeInfo {
puts "Employee #[incr i]: $id"
dict with info {
puts " Name: $forenames $surname"
puts " Address: $street, $city"
puts " Telephone: $phone"
}
}
# Another way to iterate and pick out names...
foreach id [dict keys $employeeInfo] {
puts "Hello, [dict get $employeeInfo $id forenames]!"
}AMG: [dict for] and [foreach] behave a little differently when applied to a key/value list with duplicate keys:
% set mydata {a 1 a 2 b 3 b 4}
a 1 a 2 b 3 b 4
% foreach {k v} $mydata {puts $k=$v}
a=1
a=2
b=3
b=4
% dict for {k v} $mydata {puts $k=$v}
a=2
b=4[dict for] converts the list to a dict. In the process it discards all but the last instance of each key. This doesn't mean that data is gone for good; it's still present in the string representation, so it'll reappear when the data is later used as a list or string. Amazingly, this is the case even for pure lists (lists with no string representation): the conversion to dict forces the generation of a string representation when there are duplicate keys.- DKF: That's the only way to make the semantics actually function as documented. When there are no duplicate keys, lists can go directly to dicts without losing information, but when there are duplicates, the only way to stop the Tcl value (conceptually) from mutating is to generate the string representation.
