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
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
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
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
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
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
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