Jonjilla
Jonjilla

Reputation: 463

assign a key value list to an array in Tcl

I have a list that is a key value paired list. Something like the following

key1 value1 key2 value2 key3 value3

I would like to map this to an array or a dictionary.

Currently, my code looks like this

for {set i 0} {$i < [llength $list]} {incr i} {
  if {[expr {fmod($i,2)}] == 0} {
    set key [lindex $list $i]
  } else {
    set v_array(${key}) [lindex $list $i]
  }
}

In perl, I know this can be assigned into a key value dictionary in one pass. Is there such simpler method in Tcl?

Upvotes: 2

Views: 7519

Answers (3)

Jerry
Jerry

Reputation: 71538

You can create an array in one line (I'm using one line to define the list):

% set list [list key1 value1 key2 value2 key3 value3]
key1 value1 key2 value2 key3 value3
% array set v_array $list

And if you want to check the contents, you can use parray (Tcl 8.5 and later):

% parray v_array
v_array(key1) = value1
v_array(key2) = value2
v_array(key3) = value3

And the documentation for the other array commands can be found here with examples for each.


If you somehow cannot avoid a loop, then using foreach would be easier (be sure the list has an even number of elements):

foreach {a b} $list {
  set v_array($a) $b
}

(Here foreach is taking the elements in $list two at a time and assign them to a and b)

Upvotes: 6

Mr. Bordoloi
Mr. Bordoloi

Reputation: 80

Easiest solution:

set mylist {key1 value1 key2 value2 key3 value3}
array set arr $mylist

Thats it.

Now, do a parray to check.

file: t3

#
set list [list key1 value1 key2 value2 key3 value3]
array set arr $list
parray arr
#

Execute the file: tclsh t3
arr(key1) = value1
arr(key2) = value2
arr(key3) = value3

Upvotes: 0

Dinesh
Dinesh

Reputation: 16428

You can use dict command for creating/manipulating dictionaries in Tcl.

% set mydict [dict create key1 value1 key2 value2 key3 value3]
key1 value1 key2 value2 key3 value3
% dict get $mydict
key1 value1 key2 value2 key3 value3
% dict get $mydict key3
value3
% dict get $mydict key1
value1
%

Even without the dict create command, you can straightway fetch/access the keys and values even from a list as long as it is in key-value form. i.e. even number of elements.

For example,

% set mylist {key1 value1 key2 value2 key3 value3}
key1 value1 key2 value2 key3 value3
% dict get $mylist key2
value2

As you can notice, I have not used dict create command here , but still able to access the dictionary items.

Reference : dict

Upvotes: 2

Related Questions