2

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?

3 Answers 3

6

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that looks like what I was looking for.
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.