Amumu
Amumu

Reputation: 18572

How do I set value of an entry in a nested dictionary in Tcl?

In this dict for example:

How do I change the values of fields forenames, surname, street, city and phone? I tried this way:

dict for {id info} $employeeInfo {
    puts "Employee #[incr i]: $id"
    dict with info {
        puts "   Name: $forenames $surname"
        puts "   Address: $street, $city"
        puts "   Telephone: $phone"

        set [dict get $employeeInfo $id phone] 2341

        puts "   New Telephone: $phone"

    }
}

The phone is set with a new value via:

set [dict get $employeeInfo $id phone] 12345

It doesn't work. What's the correct way to do this?

Upvotes: 2

Views: 2476

Answers (2)

Hai Vu
Hai Vu

Reputation: 40763

The phone element is under the info element, so:

dict set employeeInfo $info phone 12345

provides that you know the info element.

UPDATE

In the with context, you can set the phone element directly, try it:

dict with info {
    ...
    dict set phone 12345
    ...
}

Upvotes: 2

Donal Fellows
Donal Fellows

Reputation: 137717

The dict set command can set elements of nested dictionaries:

dict set employeeInfo $id phone 12345

Note that the enclosing dict for loop will not see the change; it (conceptually) takes a copy of the dictionary before iterating over it.

Upvotes: 2

Related Questions