Tcl - Dictionary



A dictionary is an arrangement for mapping values to keys. The syntax for the conventional dictionary is shown below −

dict set dictname key value
# or 
dict create dictname key1 value1 key2 value2 .. keyn valuen

Some examples for creating a dictionary are shown below −

#!/usr/bin/tclsh

dict set colours  colour1 red 
puts $colours
dict set colours  colour2 green
puts $colours

set colours [dict create colour1 "black" colour2 "white"]
puts $colours

When the above code is executed, it produces the following result −

colour1 red
colour1 red colour2 green
colour1 black colour2 white

Size of Dict

The syntax for getting size of dict is shown below −

[dict size dictname]

An example for printing the size is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]
puts [dict size $colours]

When the above code is executed, it produces the following result −

2

Dictionary Iteration

A simple dictionary iteration for printing keys and valued of the dictionary is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]
foreach item [dict keys $colours] {
   set value [dict get $colours $item]
   puts $value
}

When the above code is executed, it produces the following result −

black
white

Value for Key in Dict

The syntax for retrieving value for key in dict is shown below −

[dict get $dictname $keyname]

An example for retrieving value for key is given below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]
set value [dict get $colours colour1]
puts $value

When the above code is executed, it produces the following result −

black

All Keys in Dict

The syntax for retrieving all keys in dict is shown below −

[dict keys $dictname]

An example for printing all keys is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]
set keys [dict keys $colours]
puts $keys

When the above code is executed, it produces the following result −

colour1 colour2

All Values in Dict

The syntax for retrieving all values in dict is shown below −

[dict values $dictname]

An example for printing all values is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]
set values [dict values $colours]
puts $values

When the above code is executed, it produces the following result −

black white

Key Exists in Dict

The syntax for checking if a key exists in dict is shown below −

[dict exists $dictname $key]

An example for checking if a key exists in dict is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]
set result [dict exists $colours colour1]
puts $result

When the above code is executed, it produces the following result −

1
Advertisements