Eray Kuyumcu
Eray Kuyumcu

Reputation: 15

How to create nested dictionary in Tcl

I try to append or add values to an already created nested Dictionary. This is the dictionary:

set ldifValues {
    00001 {
        first abc
        second 4ee
        third 000
        nested {111-11111 111-11112}
        person 5034
    }

I try to create a new one with:

dict with ldifValues 00002 {
    lappend first abc
    lappend second 5ee
    lappend third 0101
    lappend nested 0100-5020 0100-5033 0101-50335
    lappend personnel 5033
}

I would like to add a new key started 00002 with all other values. Especially I couldn't create 00002 key as new.

Upvotes: 1

Views: 4626

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137707

You can either set things nested key by nested key:

dict set ldifValues 00002 first abc
dict set ldifValues 00002 second 5ee
dict set ldifValues 00002 third 0101
dict set ldifValues 00002 nested {0100-5020 0100-5033 0101-50335}
dict set ldifValues 00002 personnel 5033

Or you can do a bulk set by using a dictionary as the value to set:

dict set ldifValues 00002 {
    first abc
    second 5ee
    third 0101
    nested {0100-5020 0100-5033 0101-50335}
    personnel 5033
}

dict with is more suitable for updating an existing nested dictionary structure.

Upvotes: 1

Jerry
Jerry

Reputation: 71578

I would create a complex dict the following way:

set ldifValues [dict create]
dict set ldifValues 00001 {
    first abc
    second 4ee
    third 000
    nested {111-11111 111-11112}
    person 5034
}
dict set ldifValues 00002 {
    first abc
    second 5ee
    third 0101
    nested {0100-5020 0100-5033 0101-50335}
    personnel 5033
}

dict get $ldifValues 00002 personnel
# => 5033

dict set basically adds a new dict entry if the key doesn't already exists. If it exists, it will overwrite the existing key/value pair. So you can perfectly use dict set to add to an existing dict.

Upvotes: 0

Related Questions