Mr.SrJenea
Mr.SrJenea

Reputation: 523

Tcl dict modify the key name

Lets say I have a dict somedict with key1 value1

Is there a way to modify key1, let's say, to be somekey1 without removing key1 and making a new record for somekey1 ?

Upvotes: 0

Views: 1210

Answers (2)

Onel Sarmiento
Onel Sarmiento

Reputation: 1626

You can lappend new variable in dictionary and set the value from old variable to new variable then unset the old key.

set somedict [dict create key1 "black dict" key2 "white dict"]

//dict update somedict key1 varKey1 {
//    dict lappend somedict someKey1 $varKey1
//    unset varKey1
//}
//or 
set rename key1
set to someKey1
set somedict [dict replace $somedict $to {[dict get $somedict $rename][dict unset $somedict $rename]}]

set value [dict get $somedict someKey1]
puts $value

Go to TCL Dictionary for more information.

If you're looking for rename variable command there's no such thing in TCL.

Upvotes: 1

Peter Lewerin
Peter Lewerin

Reputation: 13272

You can take advantage of the fact that a dictionary is also a list, which is also a string.

Note that I will usually tell you never to mix operations and manifest types (i.e. never use, say, list operations on a string). But just like in music, in Tcl every rule can be broken if you just know what you're doing. (Except for the twelve syntactic rules, those are sacrosanct.)

Given this dictionary:

% set somedict [dict create key1 "black dict" key2 "white dict"]
key1 {black dict} key2 {white dict}

You can do a string transform:

% set somedict [string map {key1 somekey1} $somedict]
somekey1 {black dict} key2 {white dict}

And you get a new functioning dictionary:

% dict get $somedict somekey1
black dict

(The value will briefly be a string value, but it reverts to a dictionary value when you use a dictionary operation on it.)

This is a bit dangerous, though: string map will make substitutions on every match it finds, including inside longer strings.

If you know which key you want to change in order, you can use a simple list transformation:

% lset somedict 0 somekey1
somekey1 {black dict} key2 {white dict}

If you don't know where it is, you can search for it (it better be there though, otherwise lset tries to change element -1):

% lset somedict [lsearch $somedict key1] somekey1
somekey1 {black dict} key2 {white dict}

It's ugly, but it's straightforward.

Documentation: dict, lsearch, lset, string

Upvotes: 1

Related Questions