grege
grege

Reputation: 7

How do I print more than one value per key in Tcl?

array set array_in_twos {
    set1 table
    set2 chair
    set1 chair
}

foreach combo [array names array_in_twos] {
    puts "$combo is  $array_in_twos($combo),"
}

outputs:

set1 is chair,
set2 is chair,

It seems the second 'set 1' replaces the first 'set 1'. how do i print all?

set1 is table,
set2 is chair,
set1 is chair,

I'm open to other methods if using an array is not the best solution. Thanks.

Upvotes: 0

Views: 129

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137787

You can't do it with arrays or dictionaries; both are mappings from keys to values. Instead, you need to use foreach with a key-value pair system directly:

set pairs {
    set1 table
    set2 chair
    set1 chair
}

foreach {key value} $pairs {
    puts "$key is $value"
}

This does actually shorten the code…

Upvotes: 3

Related Questions